在TableView中更改行高(快速)

时间:2018-11-28 11:06:30

标签: ios swift uitableview

我在单元格中有2个Label,其中动态内容来自后端,并试图在TableView中动态更改单元格的高度。如何正确做到这一点? 这个Setting custom UITableViewCells height对我没有帮助

3 个答案:

答案 0 :(得分:1)

您可以通过2种方法完成此操作。

您可以通过在下面的代码行中进行设置来实现。

tblVW.estimatedRowHeight = 64.0
tblVW.rowHeight = UITableView.automaticDimension

使用代理人

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

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

注意:UILabel numberOfLines的自动高度应该为0,并且您的单元格UILabel上没有任何固定的高度。

答案 1 :(得分:1)

您可以使用以下两个功能:

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

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

请记住为单元格内的两个标签设置约束,否则autoDimension无效

答案 2 :(得分:1)

首先,必须确保已正确设置单元格子视图的约束,在此情况下,它们的外观应如下所示:
(有些事情您可能会错过-子标签的内容拥抱优先级已降低 ) Header constraints Sub constraints 在正确设置约束之后,我们可以继续下一步-UITableViewController(如果您的UIViewController内部带有UITableView,则您的类将看起来有所不同。我不会对此进行介绍-这是另一个主题)< / p>

您应该将ViewDidLoad函数更改为如下形式:

override func viewDidLoad() {
    super.viewDidLoad()

    // That what causes the tableView to dynamicaly set the cell's height- it will work properly only if your constraints are set properly
    self.tableView.rowHeight = UITableView.automaticDimension
    self.tableView.estimatedRowHeight = 80 // for normal conditions this type of cell would have height of 80- it's an estimated height after all...

}

就这样-这就是我使用自己的数据集时最终结果的样子

Final result

UITableViewController的最终代码:

class TableViewController: UITableViewController {

    struct ListItem{
        var header: String
        var sub: String
    }


    var ourDataHolder: [ListItem] = []

    func setupOurDataModel(){
        // Here we are setting different ListItems to our data holder, each ListItem should have a different height when displayed

        let shortListItem = ListItem(
            header: "Header",
            sub: "Sub"
        )

        let mediumListItem = ListItem(
            header: "eu mattis diam imperdiet",
            sub: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
        )

        let longListItem = ListItem(
            header: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas porttitor maximus purus quis varius. Vivamus non ornare elit. Integer nec lobortis urna. Praesent nec lorem quis libero condimentum commodo. Vestibulum elementum lacinia purus ac imperdiet. Nulla iaculis velit quis leo condimentum, eu mattis diam imperdiet. Integer quis ligula metus.",
            sub: "In vulputate magna sit amet mi faucibus luctus. Nullam finibus viverra fermentum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin ac arcu orci. Nullam lobortis augue ut purus ornare dapibus. Nulla id vehicula orci. Fusce pulvinar massa ut erat eleifend venenatis. Phasellus erat nulla, placerat a tincidunt nec, varius eu tellus. Cras quis augue non nulla elementum malesuada ut ac purus. Maecenas neque sem, tristique sit amet laoreet vitae, cursus porttitor tortor. Pellentesque tincidunt ligula vel est tempus finibus. Maecenas ac sem ac massa auctor posuere non ut tellus. Proin cursus nibh a aliquam tincidunt."
        )


        ourDataHolder = [shortListItem, mediumListItem, longListItem]
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupOurDataModel()

        // That what causes the tableView to dynamicaly set the cell's height- it will work properly only if your constraints are set properly
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.estimatedRowHeight = 80 // for normal conditions this type of cell would have height of 80- it's an estimated height after all...

    }

    // MARK: - Table view data source

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

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


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

        // be sure to set the cell's reusableIdentifier on storyboard- I've set my to "customCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableViewCell

        cell.headerLabel.text = ourDataHolder[indexPath.row].header
        cell.subLabel.text = ourDataHolder[indexPath.row].sub

        // Don't forget to set 0 for the number of lines in your label- that can be set using storyboard or programmaticaly.
        // 0 means there won't be any limitation on the maximum number of lines
        cell.headerLabel.numberOfLines = 0
        cell.subLabel.numberOfLines = 0


        return cell
    }
}

我没有添加用于另一个主题的CustomTableViewCell代码