Reputation: 25
I am using a tableview
to display a list of articles. Each cell needs to show an image and a text that has a brief descriptions of articles. What I want is to adjust the cells height depending the description length.
I know that I can resize the cells with the delegate method heightForRowAtIndexPath
but I still don’t know which height to return.
Any help?
Upvotes: 2
Views: 39
Reputation: 1760
Ok, you can do that just using Interface builder. On the Tableview properties click “Row height” automatic.
Then you can use a UILabel with property lines set to 0 to display your text. When adding the constraints to the cell you need to make sure that the height of cell depends on the intrinsic content size of the label, basically is the size of the content (the text inside the label).
For example:

Here I have added a UIImage with constant height and width and with top and leading space to 0. Also I added a UILabel with top/bottom/leading/trailing space to 0. Here the cell height will depend on the UILabel intrinsic size that is what you want. Also to prevent glitches with short texts you can add a minimum height size to the UILabel.
Of course this is an example, you can achieve the same using other constraints. The main thing here is to be aware of the concept of intrinsic content size: a predetermined size of a view based in its content.
Upvotes: 1
Reputation: 3303
The question is answered but just in case you want to know... You can return UITableViewAutomaticDimension
in heightForRowAtIndexPath
.
Nevertheless you should google more before asking a question that has been answered multiple times on the web (and on stackoverflow) ;)
Upvotes: 0
Reputation: 1297
Let's say you have a textView in each cell. The width of the textView is fixed. And you know the text for each cell. Base on the info above, you can get the height of your textView by:
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
Then you should be able to calculate the height of your cells base on your layout and stuff.
Upvotes: 1