有关UITableView--cell复用问题

 

 

近来用Tableview做了一个九宫格。过程中碰到了两个cell复用问题。

问题一:

在cell中为button添加addTarget点击事件时,出现后面的cell会重叠它前面cell的事件。代码如下:

C代码  收藏代码
static NSString *CellWithIdentifier = @"DiscoverHomeTableViewCell";  
        DiscoverHomeTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier forIndexPath:indexPath];  
        cell1.delegate = self;  
        [cell1.btnMore addTarget:self action:@selector(btnMoreDisplay) forControlEvents:UIControlEventTouchUpInside];  
        cell1.labTitle.text = @"热门";  
        cell1.listExhibit = _homeVo.listExhibit;  
        cell1.dType = D_TYPE_1;  
        cell1.navigationController = self.navigationController;  
        [cell1.tableView reloadData];  
        return cell1;

  

经过调试确实是复用了之前cell的事件。在此用协议代理可解决这一问题,用协议来进行处理点击事件。

C代码  收藏代码
#pragma mark DiscoverHomeTableViewCellDelegate  
- (void)ActionWithTap:(NSString *)type withData:(id)data{  
    if ([type isEqualToString:D_TYPE_1]) {  
        [self btnMoreDisplay];  
    }  
}  

问题二:

在UITableViewCell中,进行手写代码方式添加控件,这时在cell复用时,会出现重叠控件及控件中的内容。因为每一个cell都是重新添加的,前面的cell会覆盖在后面的cell上。于是强制对cell中添加的控件进行了清空,cell复用不变,只是新的cell加载前,都会对上一个cell的内容进行清空。代码如下:

C代码  收藏代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{  
    static NSString *CellIdentifer = @"DiscoverHomeInnerTableViewCell";  
    DiscoverHomeInnerTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:CellIdentifer forIndexPath:indexPath];  
    //TODO 解决cell复用重叠问题  
    for (UIView *subview in [cell.contentView subviews]) {  
        [subview removeFromSuperview];  
    }  
   UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
//button相关设置  
[cell.contentView addSubview:button];  
UILabel *lab = [[UILabel alloc] init];  
//lab相关设置  
[cell.contentView addSubview:lab];
原文地址:https://www.cnblogs.com/henusyj-1314/p/5984500.html