Custom UIView from Xib - requirements, good practi

2019-04-17 01:55发布

I'm trying to wrap my head around the topic of creating custom UIView using Xib files. I've done it many times, but I've never thought about why this process is so complicated, and which parts are necessary, which are good to have etc. And right now, because Xibs are the main component of the project I'm working on, I started questioning everything - I need to be sure what is happening

1条回答
够拽才男人
2楼-- · 2019-04-17 02:14

There are two approaches to loading a custom view from Nib. You either add a plain UIView in IB and set this view to a custom class (similar to how a UITableView subclass is set up). Notice File Owner is not modified in this case. When you load the nib from code you get a fully working UIView subclass directly. It's your responsibility to constraint it and add it to the view hierarchy. You cannot add this view from IB itself, as you cannot load it from IB.

The second one is to set the XIBs File Owner to the custom class. This is how UIViewControllers used to be set up prior to Storyboards. The File Owner is a proxy object in which IBOutlets will be connected to when loading. This supports being constructed both programmatically and from IB itself, you only need to put a custom UIView in any Storyboard and set its custom class to you UIView subclass and the code you add in your custom subclass will load the XIB and add its content view.

Directly answering your questions:

  • Realize the custom view has already been created from the calling code (either with MyCustomView() in code or a UIView object in IB). So to preserve its identity and constraints, the best you can do is adding a content view to it.
  • The @IBOutlet is merely a placeholder that indicates outlets will be set to this object. Actually loading the XIB must be done by your code (this is done by UIViewController for you when loading a Storyboard or in a XIB using init(nibName:bundle:) constructor)
  • The XIB has everything for the content view, not the custom view. In this approach the View in the XIB is a plain UIView and must be constrained correctly to its parent (custom view)
  • The shorter version you mentioned takes advantage of translatesAutoresizingMaskIntoConstraints to create the constraints based on a frame that is equal to the parent view.

Edit: the line self.contentView = loadViewFromNib() is irrelevant. You don't need to assign to contentView (or return anything from the loadViewFromNib method. You only need to make the connection in the XIB file and it will be set automatically upon loading. The owner: self argument indicates your custom class will be responsible for handling all connections

查看更多
登录 后发表回答