iOS学习笔记

iOS UITableView刷新某个分组或者单个cell 导致

2017-12-14  本文已影响785人  见哥哥长高了

今天项目中遇到一个特别操蛋的问题,在某个页面用到UITableView来展示一些数据(两个分组:第一个是视频播放列表,有多个视频,第二个是评论列表,有多条评论)而当我发布(删除)一条评论的时候,需要去插入(删除)一条数据,完成之后去刷新某一个cell或者一个分组,就会导致整个tableView的上下滚动。假如有人正在观看视频的话,这种效果显得非常的不友好,而且视频列表用到了重用,就会停止播放,重新显示对应的cell。
找了老半天终于找到了解决方案,tableView的其中一个代理方法,因为刷新的时候 cell的高度并不确定,则其预设高度就是个谜。

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath;

解决方法,把cell的高度缓存起来:其具体实现代码如下:

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString* key = [NSString stringWithFormat:@"%ld",indexPath.row];
    NSNumber* heigt = self.heightDic[key];
    if (heigt == nil) {
        heigt = @(100);
    }
    return heigt.floatValue;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"heig = %ld",indexPath.row);
    
    NSString* key = [NSString stringWithFormat:@"%ld",indexPath.row];
    NSNumber* heigt = self.heightDic[key];
    if (heigt == nil) {
        
        if (indexPath.section == 0) {
            NSMutableAttributedString* resetStr=[self.myViewModel.mapper.title changeLineSpaceWithSpace:ScaleWidthByOject(10)];
            CGFloat height=[resetStr sizeByFont:Font(20) andWidth:ScaleWidthByOject(345) lineSpace:ScaleWidthByOject(10)].height;
            heigt = @(ScaleWidthByOject(160) + height);
            [self.heightDic setValue:heigt forKey:key];
        }else if (indexPath.section == 1){
            if (self.myViewModel.toolType == 1 || self.myViewModel.toolType == 2) {
                cListModel *model = self.myViewModel.cList[indexPath.row];
                NSMutableAttributedString* resetStr=[model.parentContext changeLineSpaceWithSpace:ScaleWidthByOject(6)];
                CGFloat height=[resetStr sizeByFont:Font(13) andWidth:ScaleWidthByOject(315) lineSpace:ScaleWidthByOject(6)].height;
                heigt = @(ScaleWidthByOject(119)+height);
                [self.heightDic setValue:heigt forKey:key];
            }else{
                heigt = @(ScaleWidthByOject(kVideoHeight));
                [self.heightDic setValue:heigt forKey:key];
            }
        }else{
            cListModel *model = self.myViewModel.cList[indexPath.row];
            NSMutableAttributedString* resetStr=[model.parentContext changeLineSpaceWithSpace:ScaleWidthByOject(6)];
            CGFloat height=[resetStr sizeByFont:Font(13) andWidth:ScaleWidthByOject(315) lineSpace:ScaleWidthByOject(6)].height;
                    heigt = @(ScaleWidthByOject(119)+height);
                    [self.heightDic setValue:heigt forKey:key];
        }
    }
    return heigt.floatValue;
}
上一篇 下一篇

猜你喜欢

热点阅读