xib建立Cell時重用資料混亂問題解決方案
阿新 • • 發佈:2019-02-06
寫這篇文章是因為在專案中遇到了這個問題,,所以拿下來和大家一起分享,平常一直沒有因為複用問題而導致資料複用混亂,
先看看效果圖:
出現了舊的資料,所以現在這個問題就不能在使用registerNib註冊xib方法了,一般複用出現數據混亂可能原因就是cell中包含UITextField和
UICollectionView型別的資料時,出現數據混亂的情況比較大,這時候我們就需要做一些特別得操作,
思路:1:每次拿到cell進行判斷是否為nil
2:為nil就重新建立
3:不為nil時就刪除所有的子檢視
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ HistoryModel * model = self.CellModelArr[indexPath.row]; // historyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"historyCell" forIndexPath:indexPath]; historyCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //解決xib複用資料混亂問題 if (nil == cell) { cell= (historyCell *)[[[NSBundle mainBundle] loadNibNamed:@"historyCell" owner:self options:nil] lastObject]; }else{ //刪除cell的所有子檢視 while ([cell.contentView.subviews lastObject] != nil) { [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview]; } } // historyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"historyCell"]; // if (cell == nil) { // cell = [[historyCell alloc] init]; // } cell.IsBuy.hidden = YES; cell.hisModel =model; return cell; }
最後執行就發現這種解決方法是沒毛病