使用UITableViewAutomaticDimension后,所有行的高度都相同

时间:2017-01-16 23:11:48

标签: ios uitableview autolayout uitableviewautomaticdimension

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

我正在使用方法UITableViewAutomaticDimension,如下所示。但由于某些原因,当我运行模拟时,所有行都出现相同的高度。对于代码中的估计行高或我在故事板中的表视图单元格中为行高设置的数字,我输入的数字似乎并不重要。对于所有行,它总是出现相同的高度。

我在这里缺少什么?谢谢大家!

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
        }
}

` contraints simulation

1 个答案:

答案 0 :(得分:0)

您对标签没有任何限制,因此标签上没有任何内容会导致其他任何内容发生变化。您对标签没有约束的原因是您正在使用堆栈视图执行所有操作。但是堆栈视图不会从内到外神奇地调整大小。因此,他们完全阻碍你。

我建议完全删除堆栈视图。现在你能够以正常的方式做到这一点,它会起作用。