UITableview在滚动上崩溃
问题描述:
我现在被困在这个问题上好几天了,我一直没搞清楚..... 我从基于导航的模板创建了我的项目,它自动生成了一个tableview好。然后我添加了一些部分和一些行,并尝试用简单的字符串填充表格的行。这一切都可以正常工作,直到表格达到一定的长度为止。 第一行的内容也出现在最后两行,我不知道为什么... 请帮助! 这里是我的代码:UITableview在滚动上崩溃
#import "RootViewController.h"
@implementation RootViewController
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
- (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];
}
if (indexPath.section == 0) {
if (indexPath.row == 0) {
cell.textLabel.text = @"test";
}
}
return cell;
}
- (void)dealloc {
[super dealloc];
}
@end
UPDATE:
好了,所以我想我已经知道了,但我不知道发生了什么实际发生的,这只是一个巧合,但是当我改了行:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
到:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
它的工作...
有人可以向我解释这个吗? ;-)
答
正如你已经注意到的,这是由于可重复使用的单元格的工作方式。
但是,您确实应该重用您的单元格并始终在tableView: cellForRowAtIndexPath:
中重置其内容。
因此,例如,你可以这样做:
cell.textLabel.text = @"";
if (indexPath.section == 0) {
if (indexPath.row == 0) {
cell.textLabel.text = @"test";
}
}
但通常你会为每个小区适当的内容。
编辑:你真的应该阅读Table View Programming Guide,但这里是这个问题的重要摘录:
表视图的数据源实现
tableView:cellForRowAtIndexPath:
应该总是复位的重用单元时的所有内容。