Custom UIView from Xib - requirements, good practices

天大地大妈咪最大 提交于 2019-12-04 21:56:41

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!