Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Type and Self-Sizing Cells with Static Table

I have a typical master-detail app that allows the user to browse a scrolling list of objects, and then drill to detail for any particular object with a push segue. The scrolling master list is a UITableView built with prototype cells, and the detail scene is a static UITableView with a fixed number of sections and cells.

I would like to implement Dynamic Type and Self-Sizing Cells in my app so that the user can change the base font size. So far, I have been successful making self-sizing cells with the scrolling list of prototype cells: by using Auto Layout, setting number of lines in each label to 0, and setting tableView.rowHeight = UITableViewAutomaticDimension, the height of each prototype cell grows or shrinks to accommodate the size of the text within.

But I can't achieve the same effect in my static table view. Whether I use custom cells or built-in cell types, the font grows/shrinks but the cell height does not.

So my question is actually two questions: 1) is it possible to implement self-sizing cells in static table views, like I've done with my prototype table view? and 2) if the answer to the first question is no, how do I write code that will measure the height of a label in a static table view cell and adjust the cell height appropriately?

Thank you!

like image 958
protasm Avatar asked Oct 05 '15 17:10

protasm


People also ask

How to increase height of cell in tableView in iOS swift?

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property. We'll see this with the help of an sample project.

What is Uitableview in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+


2 Answers

Static table views return row height set in Interface Builder. tableView.rowHeight setting seem to be completely ignored. This is apparently a bug in UIKit.

In order to fix that, simply override -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath and return UITableViewAutomaticDimension.

like image 74
Rob Zombie Avatar answered Sep 20 '22 11:09

Rob Zombie


First add this two function in your class

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Second in order to make the UITableViewAutomaticDimension work make sure you have added all the left, right, bottom, and top constraints relative to cell container view. Also don't forget to set label's number of line to zero.

like image 44
Abhijeet Mallick Avatar answered Sep 22 '22 11:09

Abhijeet Mallick