UITableView cell的展开与收起

许多app的界面由于cell太长,需要展开与收起

  • 实现思想:
    • cell的赋值与计算高度都需要model,跟model相关,所以可以在model那设置一个属性来控制cell是展开还是收起。
    • 由于tableView的dataSource写在View里,而我的delegate写在Controller,所以需要将view里的button点击事件通过协议将其传给controller,写响应的点击事件
  • 具体实现 :
    cell的点击事件 通过代理传过去
@protocol ZJICommentsViewDelegate <NSObject>
- (void)clickFoldLabel:(UIButton *)btn;
- (void)clickShortFoldLabel:(UIButton *)btn;
@end  
- (void)clickNewsOrNo:(UIButton *)btn{
    if(self.commentsViewDelegate && [self.commentsViewDelegate respondsToSelector:@selector(clickFoldLabel:)]){
        [self.commentsViewDelegate clickFoldLabel:btn];
    }
}

controller里cell的点击事件
注意:最好不要用button.selected控制开关,可以设置一个属性控制button是什么状态 比如下面的 self.isLongSelected

- (void)clickFoldLabel:(UIButton *)btn{
    ZJILongCommitTableViewCell *cell = (ZJILongCommitTableViewCell *)[[btn superview] superview];//通过button获取父视图
    NSIndexPath *indexPath = [self.customView.tableView indexPathForCell:cell];
    ReplytoModel *reply = [self.customView.longCommentModel.comments[indexPath.row] replyto];
    if(self.isLongSelected){
        self.isLongSelected = NO;
        reply.isOpening = NO;
        
    }else{
        self.isLongSelected = YES;
        reply.isOpening = YES;
    }
    [_customView.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

在计算高度和赋值那里用model的isOpening属性
⚠️注意:在自定义cell 里layoutSubViews,先不要给self.replyToLabel.numberOfLines 赋值,这个赋值之后后面无法改变这个numberOflines属性(虽然可以改变值,但是界面无法显示改变)

if(reply.isOpening || reply.isShortOpening){
                self.replyToLabel.numberOfLines = 0;
                [self.openButton setTitle:@"收起" forState:UIControlStateNormal];
            }else{
                self.replyToLabel.numberOfLines = 3;
                [self.openButton setTitle:@"展开" forState:UIControlStateNormal];
            }

计算高度用数组缓存一下计算的高度,不用每次都算

if(replyModel && replyModel.isOpening){
                return [_cellHeightOnArray[indexPath.row] floatValue];//展开的高度
            }
            return [_cellHeightArray[indexPath.row] floatValue];//收起的高度
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值