Monday, November 13, 2017

Dynamic Height of TableView Cell

For table view in iOS, its cell could be one of several styles: basic, detail, subtitle and custom. The first 3 are built-in style. The title, subtitle, and detail are labels in the cell. By default, those labels cannot grow vertically if text in the label is too long. I found out there is a property for label to control if displaying only one or multiple lines: numberOfLines. By default, this property is one.

If you change the property to 0, the label may grow vertically to show all the text in it. That means the view cell in a table view could grow dynamically in height. This is true for the first three styles. However, for the custom view cell, it is tricky.

Recently, I was working on my iOS app to enhance its user interface. One of table views contains custom view cell. I would like to show cells in dynamic height if labels in the cell having long text. At first, I tried to set up enough constrains in the custom view cell so that no any warning nor errors in storyboard. However, my view could not show dynamic cell height.



It seems that all cell height are the same.

Finally I figured out why. The contrails in the custom view cell have to be enough for UIKit to calculate the height. In my view, I placed three labels one by one vertically. From top to bottom, I set constrains one to next vertically. However, I did not add a constrain from the last label to the bottom. As a result, UIKit could get the height of view cell.



I added the constrain to make sure the last label's bottom related to the bottom of its container. With this change, I got my app working as expected.




Enough-constrains-for-vertial-span is a trick for custom table view cell. There are other things which have to be set for dynamic cell height. See the reference blog for detail.

By the way, my app supports several languages. Therefore, for this update, I have to make all the changes in all language views in storyboard. You may notice that the messy one above is in Chinese, and the next expected one is in English. By the time I am writing this blog, I have not updated my Chinese view yet.

Reference


0 comments: