UITableView 避免UITableViewCell重用方法

問題來源:公司需求部分cell上面放定時器

主要是cell加載的時候由於重用池的問題而出現各類的bug,雖然程序沒有崩掉,可是大大影響到個人心情,下面是最主要的一個問題 ,就是cell的重用問題, cell由於從重用池中調取,沒有及時刪除上面的內容而致使內容的各類出現, 這裏有幾個解決方案.UITableView中的cell能夠有不少,通常會經過重用cell來達到節省內存的目的:經過爲每一個cell指定一個重用標識符(reuseIdentifier),即指定了單元格的種類,當cell滾出屏幕時,會將滾出屏幕的單元格放入重用的queue中,當某個未在屏幕上的單元格要顯示的時候,就從這個queue中取出單元格進行重用。spa

  • cellForRowAtIndexPath:(NSIndexPath *)indexPath
  • 經過爲每一個cell指定不一樣的重用標識符(reuseIdentifier)來解決。
  • 刪除重用cell的全部子視圖,這個方法是經過刪除重用的cell的全部子視圖,從而獲得一個沒有特殊格式的cell,供其餘cell重用。

 

代碼展現(方法一)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //改成如下的方法 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根據indexPath準確地取出一行,而不是從cell重用隊列中取出 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
     //...其餘代碼                               
}

代碼展現(方法二)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", [indexPath section], [indexPath row]];//以indexPath來惟一肯定cell 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    //...其餘代碼 
}

代碼展現(方法三)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    else 
    { 
        //刪除cell的全部子視圖 
        while ([cell.contentView.subviews lastObject] != nil) 
        { 
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview]; 
        } 
    } 
    //...其餘代碼 
}

我是用了第二種方法搞定的,讓cell的標識惟一便可,一會總結下相似於 淘寶促銷商品倒計時 最近也是遇到了一些坑,但願跟你們分享一下.code

 



做者:姚姚先生
連接:https://www.jianshu.com/p/3e7a0f574929
來源:簡書
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。orm

相關文章
相關標籤/搜索