I want to create simple custom view and use it for navigationItem.titleView. My custom view is very simple, has only image view and label: [image]-[label]. I have xib file where I have defined all constraints (both subviews has constraint to superview - I want to height and width of subviews determine height and width of entire custom view). The problem is that when I instantiate view from xib like this:
class func titleViewWithTitle(title: String, icon: UIImage?) -> TitleView {
let titleView = NSBundle.mainBundle().loadNibNamed("TitleView", owner: self, options: nil).first as TitleView
titleView.title.text = title
titleView.icon.image = icon
titleView.layoutSubviews()
return titleView
}
the size of this view is not determined by it's children. It has the size that was manually set in Interface Builder. What can I do to force the view to dynamically calculate size?
In your custom view, override the layoutSubviews method and add this:
CGSize targetSize = [self systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
Create a CGRectFrame from this and set this frame as a new frame for self (which is the custom view).
This will basically find the smallest possible frame that still encompasses its content in a way that all content is shown.
Note: All subviews of this custom view must have autolayout compression resistance set properly. I.e. they must resist shrinking.