解决Cell重用问题

时间:2023-03-10 01:19:34
解决Cell重用问题

在显示的过程中,出现了内容重叠的问题,其实就是UITableViewCell重用机制的问题。

解决方法一:对在cell中添加的控件设置tag的方法

在cell的contentView上需要添加控件,那么就可以对添加的控件设置tag,然后新建cell的时候先remove前一个cell tag相同的控件,再添加新的label,这样就不会出现cell内容的重叠。例如添加标签label

[[cell viewWithTag:100] removeFromSuperview];
[[cell contentView] addSubview:contentLabel];
解决方法二:删除cell中的所有子视图

- (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];

}

NSArray *subviews = cell.contentView.subviews;

for (UIView *subview in subviews) {

[subview removeFromSuperview];

}

以上只是列举了方法实现的位置,并没有将所有代码写出来。上面的实现方法是将cell.contentView上面的子视图全部取出来,把它们一一移除,这是解决问题的一种方法, 如果子视图过多的话,每次重用的时候都会一一把子视图移除会在程序的执行效率上产生问题。
        
        解决方法三: 通过为每个cell指定不同的重用标识符(reuseIdentifier)来解决
        重用机制是根据相同的标识符来重用cell的,标识符不同的cell不能彼此重用。于是我们将每个cell的标识符都设置为不同,就可以避免cell重用问题了。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSString *identifier = [NSString stringWithFormat:@"%d",[indexPath row]];//以[indexPath row]来唯一确定cell
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        //创建cell
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];