Reputation: 953
I'm using Swift 3, I have error adding xib file as subview
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustomView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(view);
Can someone help me please?
Upvotes: 1
Views: 411
Reputation: 592
In my Custom View Class i implemented as follow:
import UIKit
@IBDesignable class TestView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadViewFromNib(){
let view = Bundle.main.loadNibNamed("test", owner: self, options: nil)?.first as! UIView
print(view.backgroundColor ?? UIColor.blue)
}
}
then In my ViewController where i want add this custom view i write as below:
let view = TestView()
and i dont find any crash.
Upvotes: 1
Reputation: 8322
Try this, it is for swift 3.
let view = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as! UIView
self .addSubview(view)
Upvotes: 0