Create a view from .xib
let nib = UINib(nibName: "View1", bundle: nil) //View1 is a file name(View1.swift)
if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {
// logic
}
//or
if let view = Bundle.main.loadNibNamed("View1", owner: self, options: nil)?.first as? UIView {
// logic
}
Since .xib can contains several view, that is why you are working with array here(.first
)
For example
- Create View1.xib
- Create View1.swift where set owner(
loadNibNamed()
) in code to create the instance of class("View1"
)
- Set
File's Owner
in View1.xib
as View1
. Allows to connect outlets and actions
import UIKit
class View1: UIView {
@IBOutlet var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.commonInit()
}
private func commonInit() {
if let view = Bundle.main.loadNibNamed("View1", owner: self, options: nil)?.first as? UIView {
addSubview(view)
view.frame = self.bounds
}
}
}
Notes
if we move Custom Class
from File's owner
to Container View
we get error(loop). It is because of:
System init instance from Container View
where we init it again in commonInit()
.loadNibNamed
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ff7bf6fbfc8)