UITableView和UICollectionView的cell重用問題,uitableviewcell重用

來源:互聯網
上載者:User

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;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.