求助关于scrollToRowAtIndexPath 不执行

2025-05-12 18:10:39
推荐回答(1个)
回答1:

源码:

#import "ViewController.h"

@implementation ViewController
@synthesize myTableView = _myTableView;
@synthesize array = _array;
@synthesize firstResponder = _firstResponder;
@synthesize keyboardHeight;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

#pragma mark -
#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {

/*
Reduce the size of the text view so that it's not obscured by the keyboard.
Animate the resize so that it's in sync with the appearance of the keyboard.
*/

NSDictionary *userInfo = [notification userInfo];

// Get the origin of the keyboard when it's displayed.
NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

// Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
CGRect keyboardRect = [aValue CGRectValue];
self.keyboardHeight = keyboardRect.size.height; //后面要用到

// Get the duration of the animation.
NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];

// animationDuration = 0.250000
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
// 键盘高度变化通知,ios5.0新增的
#ifdef __IPHONE_5_0
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 5.0) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
#endif
NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:@"111",@"222",@"333",@"444",@"555",@"666",nil];
self.array = temp;
[temp release];
temp = nil;

self.myTableView.editing = YES;
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.myTableView = nil;
self.array = nil;
self.firstResponder = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
if (self.firstResponder != nil) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.250000];
self.myTableView.frame = self.view.bounds;
[UIView commitAnimations];

[self.firstResponder resignFirstResponder];
self.firstResponder = nil;
}
}

#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
self.firstResponder = textField;
NSLog(@"---Begin------%d",textField.tag);
[self performSelector:@selector(scrollTableView:) withObject:textField afterDelay:0.0]; //必须
return YES;
}

- (void)scrollTableView:(UITextField *)textField{
CGRect frame = self.myTableView.frame;
frame.size.height = self.view.bounds.size.height-self.keyboardHeight;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.250000];
self.myTableView.frame = frame;
[UIView commitAnimations];

int row = textField.tag-1000 == [self.array count]-1?textField.tag-1000+1 : textField.tag-1000+2;
NSIndexPath *localIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
[self.myTableView scrollToRowAtIndexPath:localIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
if (self.firstResponder != nil) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.250000];
self.myTableView.frame = self.view.bounds;
[UIView commitAnimations];

[self.firstResponder resignFirstResponder];
self.firstResponder = nil;
}
return YES;
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [self.array count]+1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selected=NO;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// }
//
// else{
// while ([cell.contentView.subviews lastObject] != nil) {
// [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
// }
// }

int row = [indexPath row];
if (row == [self.array count]) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(5, 8, 300, 34);
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[btn setTitle:@"新建" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(addRow:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
}else{

UITextField *textfield = [[UITextField alloc] initWithFrame:CGRectMake(5, 8, 300, 34)];
textfield.borderStyle = UITextBorderStyleRoundedRect;
textfield.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textfield.autoresizingMask = UIViewAutoresizingFlexibleWidth;
textfield.font = [UIFont boldSystemFontOfSize:15.0f];
textfield.placeholder = @"输入名称";
textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
textfield.returnKeyType = UIReturnKeyDone;
textfield.delegate = self;
textfield.tag = row+1000;

textfield.text = [self.array objectAtIndex:[indexPath row]];
[cell.contentView addSubview:textfield];
[textfield release];
}
return cell;
}

- (void)addRow:(id)sender{
NSLog(@"addRow...");
[self.myTableView beginUpdates];

[self.array addObject:@"未命名"];

NSIndexPath *localIndexPath = [NSIndexPath indexPathForRow:[self.array count]-1 inSection:0];
[self.myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:localIndexPath] withRowAnimation:UITableViewRowAnimationFade];

[self.myTableView endUpdates];

UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:localIndexPath];
UITextField *textfield = (UITextField *)[cell.contentView viewWithTag:[self.array count]-1+1000];
[textfield becomeFirstResponder];
}

-(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == [self.array count]) {
return UITableViewCellEditingStyleInsert;
}
else {
return UITableViewCellEditingStyleDelete;
}
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"commitEditingStyle....");
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView beginUpdates];
[self.array removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];

if (self.firstResponder != nil) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.250000];
self.myTableView.frame = self.view.bounds;
[UIView commitAnimations];

[self.firstResponder resignFirstResponder];
self.firstResponder = nil;
}
[self.myTableView reloadData];
}

if (editingStyle == UITableViewCellEditingStyleInsert) {
[tableView beginUpdates];

[self.array addObject:@"未命名"];

NSIndexPath *localIndexPath = [NSIndexPath indexPathForRow:[self.array count]-1 inSection:0];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:localIndexPath] withRowAnimation:UITableViewRowAnimationFade];

[tableView endUpdates];

UITableViewCell *cell = [tableView cellForRowAtIndexPath:localIndexPath];
UITextField *textfield = (UITextField *)[cell.contentView viewWithTag:[self.array count]-1+1000];
[textfield becomeFirstResponder];
}
}

@end