美文网首页UIiOS工程实践IOS理论知识
TableViewCell的收缩展开与动态高度

TableViewCell的收缩展开与动态高度

作者: 4d1487047cf6 | 来源:发表于2016-06-13 19:21 被阅读3234次

关于TableViewCell的收缩展开与动态高度的方法网上有很多,但本文主要运用AutoLayout和更改Constraint priority的方式来实现,另外包括了StackView动态插入在TableViewCell里的运用。

Cell收缩与展开

这是在实际项目中遇到一个需求。展示一个表格,每一行为一个项目的汇总行,点击表格每一行时展开一系列细节小行,在此点击收起该行,仅展示汇总行。如下图所示。

Paste_Image.png
Paste_Image.png
Paste_Image.png

我们用TableView去实现该需求。在点击cell时展开该cell, 再次点击时收起。不同的cell展开高度依赖于该cell所展示的内容。每一个行用StackView去实现。这里将用到嵌套的StackView和StackView动态插入。另外我用了设置约束优先级去解决Cell内容显示错位的问题。

我们先实现Cell的展开与收缩。

  • 定义一个Dictionary来存储每个Cell的展开或收缩状态。keyIndexPath
@property (nonatomic, copy) NSMutableDictionary *expandedFlagOfRowDict;
  • 每次选择cell后toggle展开状态。实现TableView delegate方法。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    BMMerchantCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    //toggle the expanded flag*
    self.expandedFlagOfRowDict[indexPath] = [NSNumber numberWithBool:![self.expandedFlagOfRowDict[indexPath] boolValue]];;
           
    [tableView beginUpdates];
    [tableView endUpdates];
}
  • 调用-beginUpdates 后 tableView delegate会回调 heightForRowAtIndexPath方法。

-beginUpdates-endUpdates 必须组合使用。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    *//cell expanded height*
    if ([self.expandedFlagOfRowDict[indexPath] boolValue]) {
        return [self.heightForRowDict[indexPath] floatValue];
    }   
    *//cell collapsed height*
    return 44;
}
  • 由此实现了Cell的展开与收缩。

Cell动态高度

上面代码我们留意到有 self.heightForRowDict 这玩意儿,每个row展开的高度是不一样的。它与self.expandedFlagOfRowDict 类似,我们定义一个字典来存储每一个Cell的高度。该字典Key为IndexPath,value为高度。

@property (nonatomic, copy) NSMutableDictionary *heightForRowDict;

而每个Cell的高度由Cell对象本身确定。我们用IB去定义Cell原型。

Paste_Image.png

Cell收缩状态时,仅展示汇总一行(即Sum Stack View)。点击展开时,显示细节行,细节行数不定。细节行嵌套到Detail Stack View这个大的StackView中。

细节行:(称之为DetailItemStackView)

Paste_Image.png

可见,在SumStackView高度已定,DetailStackView设定top与bottom约束,DetailItemStackView高度已定情况下,Cell的高度就由细节行的插入的多少决定了。

Note:与Label、Button等控件一样,Stack View 也有自己的Intrinsic Size,在未设定约束时亦能确定自己的大小。其依赖于内部subView的大小和space。在subView约束未定时其本身大小同依据于本身Intrinsic Size确定。这是一个嵌套递归的过程。

接下来就计算TableView Cell的高度。

  • 在收缩状态时,其高度等于SumStackView的高度。
  • 在展开状态时,其高度等于SumStackViewDetailStackView高度加两者距离加DetailStackViewCell.Bottom距离。

考虑到解耦与性能优化问题,Cell的高度与内容将不在Controller层计算。-tableView:heightForRowAtIndexPath: 中仅负责读取高度值。
自定义Cell对象:

//MyCell.h
@interface MyCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIStackView *detailStackView;
@property (weak, nonatomic) IBOutlet UIStackView *sumStackView;

@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UILabel *sumLabel;
@property (weak, nonatomic) IBOutlet UILabel *vLabel;

@property (assign, nonatomic) CGFloat rowHeight;

@end

先把cell的高度都设为定值,运行看看收缩与展开效果,假定rowHeight=100;

Paste_Image.png
运行时可见编译器报了一大堆约束冲突警告,界面Cell内容显示位置偏离,而IB界面设计并无约束警告。经过本人探究后发现,实际上是与运行时的 -tableView:heightForRowAtIndexPath: 代理方法返回的高度相冲突。该高度H !== sumStackView.height + space + detailStackView.height + space; 故而冲突。而将其中一个space的约束优先级调低至750,冲突解决。界面显示正常。 Paste_Image.png

Note:由此得知,-tableView:heightForRowAtIndexPath: 返回高度值的约束优先级实际上是介于7501000之间的(750<p<1000)

Cell与StackView

至此Cell展开后显示的是一个空的StackView,现在我们往Cell类里添加两个方法内容。

//MyCell.m

//Cell collapsed content
- (void)loadSumLineByDict:(NSDictionary *)dataDict {
    self.cityLabel.text = dataDict[@"cityDes"];
    self.sumLabel.text = [(NSNumber *)dataDict[@"sum"] stringValue];
}

//Cell expanded content
- (void)loadDetailLinesByDict:(NSDictionary *)dataDict {
    NSArray *detailList = (NSArray *)dataDict[@"detail"];
    
    //Insert sub stackViews. Performance consuming process.
    [detailList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *mccTag = [(NSDictionary *)obj objectForKey:@"mccTag"];
        NSNumber *num = [(NSDictionary *)obj objectForKey:@"num"];
        DetailItemStackView *itemSV = [[[NSBundle mainBundle] loadNibNamed:@"DetailItemStackView" owner:nil options:nil] lastObject];
        itemSV.mccTagLabel.text = mccTag;
        itemSV.numLabel.text = [NSString stringWithFormat:@"%@", num];
        [self.detailStackView addArrangedSubview:itemSV];
    }];
    
    [self.detailStackView layoutIfNeeded];
    [self layoutIfNeeded];
    
    //Calculate the cell's height based on AutoLayout
    CGSize size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    self.rowHeight = size.height;
}
  • 参数dataDict为数据模型;
  • -loadSumLineByDict:加载汇总行,即Cell收缩状态时的展示行;
  • -loadDetailLinesByDict:加载细节行,即Cell展开时展示的内容;该方法设计遍历以及创建StackView对象,为耗性能的步骤。这个我们让它有生之年只Run一次就够了。
  • -layoutIfNeeded在stackView们都插入完毕后,更新布局。实现Runtime时的Autolayout;
  • -systemLayoutSizeFittingSize:方法返回满足约束的大小,用以获取Cell增加内容后的高度值。

由此获取cell的datasource方法如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"MyCellID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];

    //load the collpased content
    [cell loadSumLineByDict:self.dataList[indexPath.row]];
    return cell;
}

-cellForRow:方法为高频调用,因此此处尽量进行轻量级的数据加载。此处仅加载Cell收缩状态的内容,而展开的内容则在select时加载。didSelectRow方法就变成了这样:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    *//Check if the row had been loaded. If not,*
    if (![self.loadedFlagOfRowDict[indexPath] boolValue]) {
        
        *//Load detail lines and calculate the height for row*
        [cell loadDetailLinesByDict:self.dataList[indexPath.row]];
        
        *//store the height*
        self.heightForRowDict[indexPath] = @(cell.rowHeight + 1);
        
        *//set the loaded flag to true and it will end up true ever since*
        self.loadedFlagOfRowDict[indexPath] = @YES;
    }
    
    *//toggle the expanded flag*
    self.expandedFlagOfRowDict[indexPath] = [NSNumber numberWithBool:![self.expandedFlagOfRowDict[indexPath] boolValue]];;
    
    [tableView beginUpdates];
    [tableView endUpdates];
}
  • 此处加入了一个字典属性来存储是否加载的标志位
@property (nonatomic, copy) NSMutableDictionary *loadedFlagOfRowDict;

依此判断使得该Cell展开内容有生之年仅加载一次。

  • 加载完内容后计算高度,并存储至_heightForRowDict中,在-tableView:heightForRowAtIndexPath:中读取并展示实际高度。由此实现了TableViewCell 的收缩展开与动态高度。
小结:
  • -beginUpdates & -endUpdates 实现select Cell时收缩与展开。
  • -tableView:heightForRowAtIndexPath: 的约束优先级。
  • -tableView:cellForRowAtIndexPath:-tableView:heightForRowAtIndexPath:为高频调用方法,高耗能的操作尽量转移到其它方法中,本例子中如Cell高度计算,内容加载等。本例中cellForRow方法仅加载cell最基本的内容。

下一篇讲延续本篇内容,探讨TableView的性能优化方面的问题。

相关文章

网友评论

  • 狗狗臭鸡蛋:在section可以置顶的情况下,同时在展开的情况下,我再次点击让他收缩回来,同时需要进行的操作是将当前section置顶,如何操作
  • Crayon丶_7ad1:大佬 有demo吗。。。
  • BigBossZhu:好乱啊,上面和下面有一个相同的方法写了不同的代码.能不能给个Demo
  • 84df298b2705:来个小DEMO呗。
  • 松少:没有 demo?
  • 4d1487047cf6:图有点问题抱歉,稍后我去修复。

本文标题:TableViewCell的收缩展开与动态高度

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