按照文字内容动态设置TableViewCell的高度

最近再做个项目需要使用UITableView来显示评论列表,但是有的评论字数特别多,固定的Cell高度显示不完,只能动态地根据字数来设置Cell的高度了


只要实现UITableViewDelegate的

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath方法,动态返回cell的高度


核心代码如下:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{       
    CGFloat contentWidth = self.mainTableView.frame.size.width;//得到屏幕宽度
    NSString *content = @“这里是评论的文字内容”;
    CGRect rect = [content boundingRectWithSize:CGSizeMake( contentWidth, 1000)  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];//根据content的文字,系统默认字体,字体大小为14来计算得到rect
    return rect.size.height;//只要返回上一步得到的rect的高度即可
}



要根据文字内容自动撑开TableViewCell高度,可以按照以下步骤操作: 1. 首先,在TableViewCell中添加一个UILabel,并设定好约束。 2. 在TableView的代理方法中,实现heightForRowAt方法。该方法返回值为该行的高度。在该方法中,计算UILabel的高度,并返回该高度。代码如下: ```swift func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let text = dataArray[indexPath.row] let width = UIScreen.main.bounds.size.width - 20 let font = UIFont.systemFont(ofSize: 17) let size = CGSize(width: width, height: CGFloat(MAXFLOAT)) let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byWordWrapping let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: paragraph] let rect = text.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil) return rect.height + 20 } ``` 3. 在TableViewCell中,设置UILabel的numberOfLines为0,并设定好约束。 4. 在TableView的代理方法中,实现cellForRowAt方法。在该方法中,设置UILabel的text属性。代码如下: ```swift func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let label = cell.viewWithTag(100) as! UILabel label.text = dataArray[indexPath.row] return cell } ``` 这样,就可以根据文字内容自动撑开TableViewCell高度了。其中,dataArray是存储文字内容的数组。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值