?
近來用Tableview做了一個九宮格。過程中碰到了兩個cell復用問題。
問題一:
在cell中為button添加addTarget點擊事件時,出現后面的cell會重疊它前面cell的事件。代碼如下:
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的事件。在此用協議代理可解決這一問題,用協議來進行處理點擊事件。
#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的內容進行清空。代碼如下:
- (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];
?
?