UITableView和UICollectionView的cell重用問題,uitableviewcell重用
APP的一個頁面用到了自訂的UITableViewCell,由於iOS架構的cell重用機制,遇到了一個BUG,總結一下
現象
自訂的UITableViewCell裡有一個UIButton,點擊這個button以後,需要改變cell的樣式,包括換UILabel字型顏色,禁用該UIButton等。結果發現,點擊按鈕之後,不僅當前cell的字型顏色變了,還有另外幾個cell的字型顏色也跟著變,而且是隨機的
原因
後來想到,應該是由於iOS的cell重用機製造成的,原來的代碼類似:
-(void) onButtonPressed{ label.textColor = [UIColor grayColor]; button.enabled = NO;}
其中label和button都是這個cell的執行個體變數,由於cell是自動重用的,所以其他重用此cell的格子也會跟著一起變
正確的做法
修改之後,正確的做法應該是:
1、在controller中找到此cell對應的模型
2、修改模型對應的值
3、調用tableView的reloadData方法
4、在dataSource的代理方法裡,再調用cell上的設定樣式的方法
示意代碼:
-(void) voteButtonPressed{ [myController voteWithCell:self];}
-(void) voteWithCell:(CandidateTableViewCell*)cell{ RankingView *myView = (RankingView*)self.view; // 找到對應的模型 NSIndexPath *indexPath = [myView.tableView indexPathForCell:cell]; Candidate *candidate = [candidates objectAtIndex:indexPath.row]; // 設定新值 candidate.voteCount++; candidate.isVoted = YES; // 觸發資料載入 [myView.tableView reloadData];}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ CandidateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[CandidateTableViewCell reuseIdentifier] forIndexPath:indexPath]; Candidate *candidate = [candidates objectAtIndex:indexPath.row]; [cell setCandidate:candidate isExpired:self.stage != 1 controller:self]; return cell;}