Nesting another XIB view in a XIB or storyboard is a frequently used technique. It is not always easy to get the hang of it, and the normal XIB approach to creating a view is not always enough.

Nesting a custom view in a XIB can be even more troublesome when we use Autolayout automatic layout. In this article you will learn how to nest XIB layouts and how to use some advanced uses of Autolayout in XIBs to make views have the same contrisic content size as labels.

Want to know more about the public number [iOS development stack].

Load the custom view view from the XIB

New project:

Add view and XIB to project:

Set the xib size to Freedom and set the xib size to 200×100

Set xiB Fils’ Owner to CustomView, do not set view class

Add view and set constraint in xib file

The xiB with the constraint set looks like this:

Xib establishes a link with.m

rewriteinitWithCoder:Method to add a view from the XIB

- (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; If (self) {// load xib, owner: self [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil]; self.contentView.frame = self.bounds; [self addSubview:self.contentView]; } return self; }Copy the code

Add the CustomView to main.storyboard and set the constraint

This will cause an error because the view is not constrained enough.

Let UIView have IntrinsicContentSize like UILabel

There are some views in UIKit that have intrinsicContentSize, such as UILabel, UIButotn, UIImageView, etc. Such views can be sized based on their contents, and only need to determine the position (x/y) when setting constraints.

UIView itself does not have this feature, but we can tell the compiler that the current view is self-sizing by setting intrinsicSize in the XIB or storyboard.

This way, there is no warning of insufficient constraints.

Finally, the customView display in view Controller is what it looks like in.xib.

conclusion

From this article we can learn:

  • Xib custom view methods
  • Make UIView have IntrinsicContentSize methods like UILabel
  • Xib nested methods used

The article was first posted on my iOS tech blog.

More quality iOS development related content can be viewed at my official account [iOS development Stack].