美文网首页基础知识iOS UI开发
Cell的折叠和展开(主要针对Cell上的label文字内容)

Cell的折叠和展开(主要针对Cell上的label文字内容)

作者: HuangLinWang | 来源:发表于2016-11-05 22:42 被阅读413次
demo.gif

思路

  • 自定义Cell 对控件进行布局,约束参考Cell.contentView
    • 目的是为了自动计算行高
  • UItableViewController控制器设置自动计算行高
      //预估行高
      self.tableView.estimatedRowHeight = 100;
      //指定计算行高
      self.tableView.rowHeight = UITableViewAutomaticDimension;
  • 当Cell能够根据内容自动计算行高以后,需要考虑的就是label的行数了
        // 多行
        label.numberOfLines = 0;
        // 1行
        label.numberOfLines = 1;
  • 提供一个按钮,添加点击事件.点击按钮修改label的行数,并发送通知(通知将Cell自身传递过去),让UItableViewController监听通知
        -(void)clickBtn{
            
            if (self.contentL.numberOfLines == 1) {
                self.model.numberOfLine = 0;
            }else{
                self.model.numberOfLine = 1;
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"XXXX" object:self];
        }
  • UItableViewController监听通知
        // 监测通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lwReloadData:) name:@"XXXX" object:nil];
  • UItableViewController实现通知事件-> 根据传递的Cell获取Cell对应的indexPath,刷新对应的indexPath(这样做是为了处理Cell复用问题)
        -(void)lwReloadData:(NSNotification *)noti{            
            LWTableViewCell *cell = [noti object];            
            NSIndexPath *index = [self.tableView indexPathForCell:cell];            
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];            
        }
  • 你以为这样就好了?NO,还是有复用问题存在.怎么办?
    给Cell对应的模型添加一个属性.这个属性用来记录label的行数,Cell复用传值的时候就会对,Cell的内容属性的label行数进行赋值.这样就不会存在复用问题了.
      -(void)setModel:(LWModel *)model{
            _model = model;
            self.icon.image = [UIImage imageNamed:model.icon];
            
            self.nameL.text = model.name;
            
            self.contentL.text = model.intro;
            // 对Cell的内容属性的label行数进行赋值
            self.contentL.numberOfLines = model.numberOfLine;
        }
  • 细节->加载数据的时候 给属性numberOfLine设置一个值
        -(void)loadData{
            
            NSData *data = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"MessageSource.json" withExtension:nil]];
            
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            NSMutableArray *arrM = [NSMutableArray array];
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                LWModel *model  = [LWModel lwModelWith:obj];
                // 设置为1 是为了让label默认显示1行
                model.numberOfLine = 1;
                [arrM addObject:model];
            }];
            _dataList = arrM.copy;
        } 

相关文章

网友评论

    本文标题:Cell的折叠和展开(主要针对Cell上的label文字内容)

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