显示更多按钮操作的动态标签和单元格高度

Posted

技术标签:

【中文标题】显示更多按钮操作的动态标签和单元格高度【英文标题】:Dynamic label and cell height with show more button action 【发布时间】:2017-04-13 05:22:01 【问题描述】:

我试图在点击显示更多按钮标签后在tableViewCell 中实现动态标签高度需要设置label.numberOfLines = 0

那么单元格高度和标签高度应该动态增加。

下面是我的代码(当tableView 重新加载相同的标签高度以用于重复使用的单元格时)

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

 let cell: UITableViewCell = 
 self.tableView.dequeueReusableCell(withIdentifier: 
 "BTSTableViewCellIdentifier")! 
    cell.configureWithPost(posts[indexPath.row])
    cell.delegate = self
    return cell
   

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: 
  IndexPath) -> CGFloat 
    return UITableViewAutomaticDimension


func tableView(_ tableView: UITableView, estimatedHeightForRowAt 
 indexPath: IndexPath) -> CGFloat 
    return UITableViewAutomaticDimension



func configureWithPost(_ postViewModel: BTSTableCellViewModel) 
    self.postViewModel = postViewModel
    usernameLabel.text = postViewModel.username
    detailtextLabel.numberOfLines = 2
    detailtextLabel.text = postViewModel.textDetail  


@IBAction func showmorePressed(_ sender: Any) 
    detailtextLabel.numberOfLines = 0;
         self.tableView.reload()


【问题讨论】:

返回 UITableViewAutomaticDimension 在按下时索引路径的行的高度 ViewMore 否则返回一些静态高度 @Bharath 问题修复了吗? 我已经实现了行的高度。但是,我仍然遇到了问题。 @Ganesh @Bharath 你在使用 swift 3 吗?然后 tableview.reloadData 它应该是....还检查是否通过放置断点来调用 showMorePressed 动作。 【参考方案1】:

您还需要在 heightForRowAtIndexPath 中管理高度:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
        return UITableViewAutomaticDimension
    

同样在showMore按钮动作中,

@IBAction func showmorePressed(_ sender: Any) 
    detailtextLabel.numberOfLines = 0;
         self.tableView.reloadData()

【讨论】:

我仍然遇到同样的问题。你能帮我解决这个问题吗?【参考方案2】:
CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@NSFontAttributeName:label.font
                                              context:context].size;

size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

【讨论】:

以上是关于显示更多按钮操作的动态标签和单元格高度的主要内容,如果未能解决你的问题,请参考以下文章

单元格标签中的最后一行不会出现自动布局和动态单元格高度

如何动态更改自定义单元格的表格视图单元格的高度?

基于动态标签高度的 iOS8 动态单元格高度

动态单元高度问题

动态单元格高度的自动布局约束

在单个单元格中显示页眉页脚和单元格?