9
votes

Setting estimatedRowHeight and rowHeight of UITableView makes the table view calculate proper height of each cell. That works like a charm until I use size classes. It seems like all the calculations are being done for Any/Any size class and the bigger font is applied later. As a result the height of the cell is not properly calculated and the label doesn't fit.

Here is my code:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.estimatedRowHeight = 50
        self.tableView.rowHeight = UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Reuse", forIndexPath: indexPath) as! MyTableViewCell
        println("Label font size: \(cell.myLabel.font)") // it prints (...)font-size: 11.00pt for all the size classes
        return cell
    }
}

Layout looks like that: Table view layout

And the usage of size classes is: Font size classes

Now, when I open the app on an iPhone everything looks like expected. But on an iPad the cells are not properly resized. In fact they are resized to fit the text if it was font size 11pt instead of 40pt.

The question is: How can I force the calculations to be performed after the size classes were applied?

I already tried the trick with overriding trait collection as suggested in: https://stackoverflow.com/a/28514006 but it didn't work. I mean, the size class was read properly (Regular/Regular) but the font size was still 11pt.

You can download this simple project from Github: https://github.com/darecki/TableViewTest

Screenshots:

  • iPhone 4s:

enter image description here

  • iPad 2:

enter image description here

  • iPad 2 after calling tableView.reloadData():

enter image description here

Edit: Formatting, added Github link.

1
It is set to 0. I added screenshots to show how it does behave.Darek Cieśla
set the label's font in your custom cell's awakefromnib() based on device typedopcn
can you share your sample code?Johnykutty
Sure! You can find it here: github.com/darecki/TableViewTestDarek Cieśla
I've confirmed that this is not working on iOS 8.4 but work flawlessly on iOS 9. What did change between those?Ertai

1 Answers

-3
votes

Set preferred max width on the label in Interface Builder - > Size inspector. This solves the issue for me. Also make sure number of lines is 0.