Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

ios - UITableViewCell auto height based on amount of UILabel text

I have a bit of a tricky set up in my storyboard, I have a UIViewController that holds a UITableViewController. Within the UITableViewController I have several prototypecells I have linked to subclassed uitableviewcell objects in code.

Using constraints and storyboard I would like to change the height of my prototype cell depending on the size the UILabel ends up being which is dependant on the text going into it.

Currently I have a

UIViewController
-- UITableViewController
-- -- UITableViewCell ((melchat) prototype cell)
-- -- -- ContentView
-- -- -- -- UIView ((background) view with drop shadow card type effect)
-- -- -- -- -- UIImageView (Avatar)
-- -- -- -- -- IUlabel (dynamic (depending on code/input) multi line UILabel)

Some how I would like the UILabel to resize the UIView (background) then in turn effect the height of that UITableViewCell.

I am using XCode 8.2.1

I have taken a screen shot of the layout in storyboard and constraints applied.

enter image description here

Update

I have updated my constraints to pretty much all go back to ContentView and have updated uilabel line count to 0 and then also implemented the UITableViewAutomaticDimension code but its still not working. Please see code and screen shots below.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;

}

enter image description here

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To go a little further on Dao's answer..

He is correct, you need to use UITableViewAutomaticDimension

Also, you need to ensure that you setup your constraints in a way that all of the content in the cell is constrained to the cells contentView. So your label will likely need constraints such as

  • Leading constraint to ImageView
  • Top constraint to contentView
  • Bottom constraint to contentView
  • Trailing constraint to contentView

Make sure that you set the UILabel to multiline (or lines = 0) and it should work.

If you are using the heightForRowAt delegate functions ensure you return UITableViewAutomaticDimension


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...