You want to make the restrictions of AutoLayout as simple as possible. By loading Xib into View, the constraints in ViewController are made simpler! And simplify.
First, place the View in sampleViewController.Xib
.
After placing the View like this, create a Swift file and a View Xib file.
Swift file View Xib file
Let's use the same file name! !! (Named sampleHomeView this time)
Write the code in sampleHomeView.swift
. This is OK with copy and paste.
sampleHomeView.swift
import UIKit
class sampleHomeView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
loadView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadView()
}
private func loadView() {
let className = String(describing: type(of: self))
let view: UIView = Bundle.main.loadNibNamed(className, owner: self, options: nil)?.first as? UIView ?? UIView()
view.frame = bounds
addSubview(view)
}
}
By writing this code, you can set the class of File's Owner and load it into View.
Select File's Owner in sampleHomeView.Xib
and set Class to sampleHomeView.
Then place the UI parts in sampleHomeView.Xib
. (Place Button this time)
Next, set sampleView.Xib
.
Select the View you placed first and set the Class of CustomClass to sampleHomeView.
Now you can load Xib into View.
However, in this state, we do not know that it is loaded in View, so let's build it! !!
You could load it with this (^ ^) By doing this, it seems that the layout of UI parts can be simplified.
Recommended Posts