I\'m trying to learn auto layout, finally thought I was getting the hang on it when this happened. I\'m playing about with prototype cells and labels. I\'m trying to have a
Found an even better answer after reading this: http://johnszumski.com/blog/auto-layout-for-table-view-cells-with-dynamic-heights
creating a UILabel subclass to override layoutSubviews like so:
- (void)layoutSubviews
{
[super layoutSubviews];
self.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
[super layoutSubviews];
}
This ensures the preferredMaxLayoutWidth is always correct.
Update:
After several more release's of iOS and testing more usecase's i've found the above to not be sufficient for every case. As of iOS 8 (I believe), under some circumstances only didSet bounds was called in time before the screen load.
In iOS 9 very recently I came across another issue when using a modal UIVIewController with a UITableView, that both layoutSubviews and set bounds were being called after heightForRowAtIndexPath. After much debugging the only solution was to override set frame.
The below code now seems to be necessary to ensure it works across all iOS's, controllers, screen sizes etc.
override public func layoutSubviews()
{
super.layoutSubviews()
self.preferredMaxLayoutWidth = self.bounds.width
super.layoutSubviews()
}
override public var bounds: CGRect
{
didSet
{
self.preferredMaxLayoutWidth = self.bounds.width
}
}
override public var frame: CGRect
{
didSet
{
self.preferredMaxLayoutWidth = self.frame.width
}
}