insertRowsAtIndexPaths Doesnot call cellForRowAtIndexPath
问题描述:
我创建了示例tableview应用程序,并且我在桌面视图上方有一个添加按钮,当用户只按下添加按钮时,我们希望将行添加到表视图。insertRowsAtIndexPaths Doesnot call cellForRowAtIndexPath
我很喜欢这个
- (void)viewDidLoad {
isEditing = NO;
Mutarray = [[NSMutableArray alloc]init];
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (isEditing)
return [Mutarray count];
else
return 0;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
[TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
NSLog(@"Row = %d", indexPath.row);
// Configure the cell...
cell.textLabel.text = [Mutarray objectAtIndex:indexPath.row];
return cell;
}
//When add button pressed
-(IBAction)Add:(id)sender
{
isEditing = YES;
[Mutarray addObject:[NSString stringWithFormat:@"%d",[Mutarray count]]];
NSArray *insertIndexPaths = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:[Mutarray count]-1 inSection:0],
nil];
[self.TableView beginUpdates];
[self.TableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationRight];
[self.TableView endUpdates];
}
此代码的工作fine.But问题是我的tableview高度为418,它只显示10行作为可见写代码。所以当11行被添加它添加在tableview中,但没有调用这个cellForRowAtIndexPath函数,所以我无法自动滚动页面...前10行它调用cellForRowAtIndexPath函数。
所以我怀疑为什么cellForRowAtIndexPath函数只调用可见行? 那我该如何自动滚动我的tableview?
答
所以我我的疑惑是为什么 的cellForRowAtIndexPath功能仅 调用可见行?
这是因为优化的原因。如果表视图为其所有行创建了单元格,则会显着降低性能。而不是该表视图创建的单元格仅适用于可见的行(并且可能需要更多才能确保平滑滚动),然后重用它们以显示可见的行 - 实际上,您可以显示数百行只有10个单元格对象 - 这是一个巨大的保存。
那我该如何自动滚动我的 tableview?
你在add
方法添加了行后,您可以向右滚动:
...
[table endUpdates];
[table scrollToRowAtIndexPath:[insertIndexPaths objectAtIndex:0]
atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
附:传统上Objective-C中的方法和变量名称以小写开头,遵循该准则是更好的样式。
谢谢弗拉基米尔。看起来不错 – dragon 2010-07-27 09:53:10