简体   繁体   中英

How do I change cell height according to its content?

I have a Detail View Controller, which has different text lengths according to which cell you press in the Main View Controller, of which it segues to. How do I set the cell's height according to how much content is in it?

FYI, the cell consists of 3 labels and 1 image view. It is vertically set as UILabel , UIImageView , UILabel , UILabel .

I am using Swift.

This is what happens when I add the auto-layout constraints:

The way to do it is to use auto-layout. You need to set up vertical constraints from the top to the bottom of your cell:

  1. Distance between the top edge of the cell and the top edge of the first label.
  2. Distance from the bottom edge of the first label to the top edge of the image view.
  3. Distance from the bottom edge of the image view to the top edge of the second label.
  4. and so on ...

Auto-layout will take care of sizing the cell depending on the size of the content you put in your labels and the image view.

You should also remember to set the estimatedRowHeight property on your table view to some meaningful value. This will help the table view defer some of the calculations of the content size to when the user starts to scroll.

Also, set the rowHeight property on your table view to UITableViewAutomaticDimension .

There are 4 things you'll need to do:

  1. Set your tableView:heightForRowAtIndexPath method to return UITableViewAutomaticDimension .
  2. Set your tableView:estimatedHeightForRowAtIndexPath to return the average height of the cells. You can set it to something static like 100.
  3. Set your Auto Layout constraints so that all subviews are tied to each other vertically, and the top-most and bottom-most views are tied up to the cell's contentView .
  4. Set the label's preferredMaxLayoutWidth property either in code or in your Storyboard to be equal to the label's width.

为了解决这个问题,我在标签中添加了sizeToFit()属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM