Max Levi
Max Levi

Reputation: 13

Change row height in TableView (swift)

I've got 2 Label in cell with dynamic content coming from backend and trying to make dynamic changing height of cell in TableView. How to correctly do this? This Setting custom UITableViewCells height doesn't help me

Upvotes: 1

Views: 9490

Answers (3)

Niv
Niv

Reputation: 547

First, you got to make sure you've set the constraints of the cell's subviews properly, for your case here how they should look like:
(Something you'll probably miss- the sub label's Content Hugging Priority has been decreased ) Header constraints Sub constraints After you've set your constraints properly, we can proceed to the next step- our UITableViewController (if you got a UIViewController with a UITableView inside him, your class will look different. I'm not covering this- that's for another topic)

You should change your ViewDidLoad function to look like this:

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

}

So that's it- here's how the final result looks like when I've used my own dataset

Final result

Final code of 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
    }
}

I'm not adding the CustomTableViewCell code- that's for another topic

Upvotes: 3

Francesco Destino
Francesco Destino

Reputation: 349

You can use this two function:

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

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

Remember to set the constraints for your two label inside the cell or the automaticDimension won't work

Upvotes: 3

Denis
Denis

Reputation: 492

You can do this by 2 ways.

You can do this by setting below lines of code.

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

by using Delegates

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

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

Note: UILabel numberOfLines shoud be 0 for auto height and there's no any fixed height set to your cell UILabel.

Upvotes: 6

Related Questions