前言:
UITableView中的cell可以有很多,一般会通过重用cell来达到节省内存的目的:通过为每个cell指定一个重用标识符(reuseIdentifier),即指定了单元格的种类,当cell滚出屏幕时,会将滚出屏幕的单元格放入重用的queue中,当某个未在屏幕上的单元格要显示的时候,就从这个queue中取出单元格进行重用。但对于多变的自定义cell,有时这种重用机制会出错。
1、错误:
最近一个人在自主开发软件,今晚在tableview上使用自定义cell时遇到一个问题:每次上下滚动tableview时,当自定义的cell滚回可见范围内时会被打乱,甚至会消失,如图:
2、解决方法:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
改为以下的方法:
UITableViewCell *cell = [tableViewcellForRowAtIndexPath:indexPath];
注 : 重用机制调用的就是dequeueReusableCellWithIdentifier这个方法,方法的意思就是“出列可重用的cell”,
因而只要将它换为cellForRowAtIndexPath,就可以不使用重用机制,
因而问题就可以得到解决,虽然可能会浪费一些空间。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //改为以下的方法
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];//根据indexPath准确地取出一行,而不是从cell重用队列中取出
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//...其他代码
}
方法 ②:
通过为每个cell指定不同的重用标识符(reuseIdentifier)来解决
注: 重用机制是根据相同的标识符来重用cell的,标识符不同的cell不能彼此重用。
于是我们将每个cell的标识符都设置为不同,就可以避免不同cell重用的问题了。