cell高度自适应(做聊天气泡)

- (NSInteger)autoWithAndHeight:(NSString *)string {
    UIFont *font = [UIFont systemFontOfSize:18];
  CGRect autoRect = [string boundingRectWithSize:CGSizeMake(150, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font}  context:nil];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, autoRect.size.width, autoRect.size.height)];
    label.numberOfLines = 0;
    
    return label.bounds.size.height ;
}

上面的方法是返回一个字符串根据UILable自适应的高度

协议方法返回cell的高度(根据_dataSource里面字符串的大小)+ 40是因为我上面有个日期(时间)

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

    
    return [self autoWithAndHeight:_dataSource[indexPath.row]] +40;
}

做气泡的背景 (重写cell)

        _rightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.contentView.bounds) - 120, 30, 150, 60)];
        _rightImageView.layer.cornerRadius = 10;
        _rightImageView.clipsToBounds = YES;
        _rightImageView.backgroundColor = [UIColor someColor:0 green:178 blue:64];
          [self.contentView addSubview:_rightImageView];
        _labeltext = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.contentView.bounds) - 120, 30, 150, 60)];
        _labeltext.numberOfLines = 0;
        _labeltext.text = @"测试是是是是是是";
        _labeltext.layer.cornerRadius = 10;
        _labeltext.clipsToBounds = YES;
        _labeltext.backgroundColor = [UIColor someColor:0 green:178 blue:64];
        [self.contentView addSubview:_labeltext];

需要在外面更改 frame

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    //选中无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //线条无色
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    cell.labeltext.text = _dataSource[indexPath.row];
    cell.labeltext.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 190, 30, 150, [self autoWithAndHeight:_dataSource[indexPath.row]]+5);
    cell.rightImageView.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 200, 30, 170, [self autoWithAndHeight:_dataSource[indexPath.row] ]+5);

效果图,效果不是很好,有时间优化一下




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值