ios - 自动调整自定义 UITableViewCell 的大小

标签 ios swift uitableview

我有一个自定义表格 View 单元格,我想根据标签中的文本量自动调整其大小。

这是我的手机。我想调整它的大小以显示评论标签中的所有文本。 enter image description here

在我的 TableView Controller 中,我使用 UITableViewAutomaticDimension

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return 200
            } else {
                return 49
            }
        } else if indexPath.section == 1 {
            return 100
        } else if indexPath.section == 2 {
            if indexPath.row == 0 {
                return 200
            } else {
                return 400
            }
        } else {
            return UITableViewAutomaticDimension
        }
    }

    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

这就是我最终得到的结果。

enter image description here

最佳答案

您需要:

  1. 将标签的top、trailing、leading、bottom约束设置为IB中的superView
  2. 设置numberOfLines = 0
  3. 设置内容抗压缩优先级垂直内容拥抱优先级垂直
  4. 在代码中设置self.tableView.estimatedRowHeight = MinControlSize; self.tableView.rowHeight = UITableViewAutomaticDimension;

设置文本后调用此

cell.setNeedsDisplay();
cell.layoutIfNeeded();

在委托(delegate)方法中

optional func tableView(_ tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

希望这有帮助。我从 Apple 的“ self 调整大小”示例中获取此内容

关于ios - 自动调整自定义 UITableViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705094/

相关文章:

xcode - Parse.com 入门项目在 xcode 6.3 上出现 Cannot invoke 'subscribeToChannelInBackground' 编译器错误

swift - 从 XIB OS X App 添加(addsubview)自定义/可重用 View

ios - UIVisualEffectView 和 UITableView

ios - 未在 UITabBarController 内部调用 cellForRowAtIndexPath

iphone - 如何在按下按钮时动态更新 UITableView?

swift - NSImage 到 Base64 字符串丢失质量

ios - Parse 如何处理指向同一个 PFObject 的多个指针

ios - 解压从 GitHub 下载的 zip 文件时出现错误 63(文件名太长)

java - 如何理解面向对象编程中的 "reference"?

ios - 使用 Realm 文件预填充 Realm 数据库