I have a tableview with a label and an image. in some cells, there is no image as i used imageView.removeFromSuperview()
to remove it from the cell. When there is an image in the cell, the row height is 445 and "Custom" is checked off.
how can i set the row height dynamically according to how long the label is instead of how long/big the imageview is after i remove the imageview?
If you want dynamic row height, you can define your constraints (making sure they're unambiguous), set the label's
numberOfLines
to zero, and then inviewDidLoad
, tell it that rows should automatically adjust their height:If you want to hide/show a
UIImageView
as well, I must confess that I'm not crazy about theremoveFromSuperview
approach (because when the cell is reused, you have to re-add the image view, and possibly rebuilding its constraints, too) there are a few options:You could have a different cell prototype for the cell with the image view and another without the image view. Then
cellForRowAtIndexPath
just needs to instantiate the right cell.You could go ahead and define a full set of constraints that are unambiguous for both the presence of the image and without the image. And then, you can
activate
the constraint and set the image view tohidden
as appropriate:The trick when having competing sets of constraints that dictate the height of the cell is to just make sure that they have different priorities and/or they use inequality so if both sets are in effect, you don't have an unsatisfiable conflict (e.g. the image view might have higher priority).
You can, if you want, go "old school" and programmatically determine the size of the label field, and then implement
heightForRowAtIndexPath
, but auto layout makes this process unnecessary.You need to override this method:
Return the desired height for the indexPath you want in this method
If you're using UILabel, it has a frame with a height property.
And heightForRowAtIndexPath, should cover what you're wanting for the appropriate method to use: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath:
not sure how your image is currently set up, but here's a rough example: