使用 UITableViewAutomaticDimension 后行的高度都相同

Rows all same height after using UITableViewAutomaticDimension

我试图根据该单元格中标签中的文本行,使 table 中的所有行都有自己的行高。我的出发点是这里的 Wenderlich 教程: https://www.raywenderlich.com/129059/self-sizing-table-view-cells

我正在使用 UITableViewAutomaticDimension 方法,如下所示。但是由于某种原因,当我 运行 模拟时,所有行的高度都相同。我在代码中为估计行高输入的数字或在故事板的 Table View Cell 中为行高输入的数字似乎无关紧要。所有行的高度始终相同。

我在这里错过了什么?谢谢大家!

import UIKit

class LoLFirstTableViewController: UITableViewController {

    var tasks:[Task] = taskData

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 60.0
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }

    @IBAction func cancelToLoLFirstTableViewController(_ segue:UIStoryboardSegue) {
    }

    @IBAction func saveAddTask(_ segue:UIStoryboardSegue) {
        if let AddTaskTableViewController = segue.source as? AddTaskTableViewController {

            if let task = AddTaskTableViewController.task {
            tasks.append(task)

                let indexPath = IndexPath(row: tasks.count-1, section: 0)
                tableView.insertRows(at: [indexPath], with: .automatic)
            }
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
    -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath)
        as! TaskCell
        let task = tasks[indexPath.row] as Task
            cell.task = task
        return cell
        }
}

`

您对标签没有任何限制,因此标签不会导致任何其他更改。你对标签没有限制的原因是你正在用堆栈视图做所有事情。但是堆栈视图不会从内到外神奇地调整大小。因此,他们完全妨碍了您。

我建议完全消除堆栈视图。现在您将能够以正常方式执行此操作,并且它会起作用。