I'm currently working on a social media app (basic like Facebook) and I'm having the hardest time working with autolayout. I used to do it using frames and stuff, but since my whole project uses autolayout, I'd like to try and make it work that way.
Basically, I've got a cell with some informations on top, a UILabel below (that contains the user's status), a view below (that can contain anything from a UIImage to a web view. It acts as a container) and a bar on the bottom with actions buttons (like/share and stuff).
I use the same cell for any content (text only, image, video and webpage). What I though I would do is when the user only shares a status, I remove the container view (or hide it), and on other cases, I start with :
- calculating the status' label height from the status' text using boundingRectWithSize
- depending on the feed type (text, image, etc.), I calculate the whole cell height
The cell height work pretty fine. I'm having difficulties with the status text label.
At first, I tried to set the label's height in the cellForRowAtIndexPath using a setFrame. It did not work.
After that, I tried to calculate the label's height directly in the cell. I called this method in the layoutSubviews of the cell
- (void)resizeStatusTextField
{
NSString* text = self.feedTextLabel.text;
CGRect rect = [text boundingRectWithSize:CGSizeMake(300, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: self.feedTextLabel.font} context:nil];
NSDictionary* views = NSDictionaryOfVariableBindings(_containerView, _feedTextLabel);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[_containerView]-46-[_feedTextLabel(%f)]", rect.size.height] options:0 metrics:nil views:views]];
[self setNeedsUpdateConstraints];
}
So what I tried to do is settings the feedTextLabel constraints to 46 points below it's container's top and settings the calculated size.
It's seems to work more or less (thought I'm not sure it is the right way to do it) but now whenever I scroll, the text content disappears.
If someone can point out to me the correct way to manage such dynamic constraints inside tableView, it would be much appreciated.
Thanks.
EDIT : I of course read posts like "Using Auto Layout in UITableView for dynamic cell layouts & variable row heights", but I believe my case is pretty peculiar since I got multiple views that can have dynamic heights inside the cell. So please don't mark this post as duplicate ;) Thanks