- (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);
效果图,效果不是很好,有时间优化一下