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
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- Using if let syntax in switch statement
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
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:
init(nibName:bundle:)
constructor)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 tocontentView
(or return anything from theloadViewFromNib
method. You only need to make the connection in the XIB file and it will be set automatically upon loading. Theowner: self
argument indicates your custom class will be responsible for handling all connections