UIiOS工程实践IOS理论知识

TableViewCell的收缩展开与动态高度

2016-06-13  本文已影响3234人  4d1487047cf6

关于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的展开与收缩。

@property (nonatomic, copy) NSMutableDictionary *expandedFlagOfRowDict;
- (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-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动态高度

上面代码我们留意到有 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的高度。

考虑到解耦与性能优化问题,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;
}

由此获取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展开内容有生之年仅加载一次。

小结:

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

上一篇 下一篇

猜你喜欢

热点阅读