美文网首页iOS头条干货iOS知识收藏
教你如何友好的避免cell重用(滑动后cell错乱)

教你如何友好的避免cell重用(滑动后cell错乱)

作者: 姚姚先生 | 来源:发表于2017-04-25 19:04 被阅读392次

问题来源:公司需求部分cell上面放定时器

主要是cell加载的时候因为重用池的问题而出现各种的bug,虽然程序没有崩掉,但是大大影响到我的心情,下面是最主要的一个问题 ,就是cell的重用问题, cell因为从重用池中调取,没有及时删除上面的内容而导致内容的各种出现, 这里有几个解决方案.UITableView中的cell可以有很多,一般会通过重用cell来达到节省内存的目的:通过为每个cell指定一个重用标识符(reuseIdentifier),即指定了单元格的种类,当cell滚出屏幕时,会将滚出屏幕的单元格放入重用的queue中,当某个未在屏幕上的单元格要显示的时候,就从这个queue中取出单元格进行重用。

  • cellForRowAtIndexPath:(NSIndexPath *)indexPath
  • 通过为每个cell指定不同的重用标识符(reuseIdentifier)来解决。
  • 删除重用cell的所有子视图,这个方法是通过删除重用的cell的所有子视图,从而得到一个没有特殊格式的cell,供其他cell重用。
443492BA-6FDF-4221-A030-569B8A6C92E8.png

代码展示(方法一)

- (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的标识唯一即可,一会总结下类似于 淘宝促销商品倒计时 最近也是遇到了一些坑,希望跟大家分享一下.

相关文章

网友评论

    本文标题:教你如何友好的避免cell重用(滑动后cell错乱)

    本文链接:https://www.haomeiwen.com/subject/gtxbzttx.html