首页 > 解决方案 > UITableView 自动维度无法正常工作

问题描述

我有一个表格视图,其中填充了来自 Firebase 的数据。但是,当使用自动尺寸调整 tableview 的大小时,一些文本显示被截断。

这是我的故事板,其约束设置为顶部、底部、右侧和左侧。

在此处输入图像描述

当此处显示的文本不多时,它工作正常。

在此处输入图像描述

但是,当我用大量文本填充单元格时,就会发生这种情况。

在此处输入图像描述

这是我目前正在使用的代码。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (tableView == questInformationTableView) {
            return 50
        }
        else if (tableView == questWalkthroughTableView) {

            return UITableView.automaticDimension
        }

        return 0
    }
    override func viewDidLoad() {
          super.viewDidLoad()
          questWalkthroughTableView.estimatedRowHeight = 250
          questWalkthroughTableView.rowHeight = UITableView.automaticDimension
        }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
         return UITableView.automaticDimension
        }

我还将 numberOfLines 设置为 0 并将标签设置为 .sizeToFit()

标签: iosswiftxcodeuitableviewautomaticdimension

解决方案


我通常设置自动高度尺寸,然后像这样在 viewDidLoad 中重新加载

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44

    tableView.reloadData()   
}

推荐阅读