Reputation: 292
I have a XIB with a custom class ProfileHeaderView. I also have ProfileViewController and ProfileTableViewCell, both with IBOutlet profileHeader.
What I want is to load nib into profileHeader . So far I do it by loading NIB and then adding it as a subview of profileHeader which I guess is not the best solution and i have to set frame manually.
let view = NSBundle.mainBundle().loadNibNamed("ProfileHeaderView", owner: self, options: nil).last as! ProfileHeaderView
view.setFrame(...)
self.profileHeaderView.addSubview(self.view)
What's the best way to achieve it?
Upvotes: 0
Views: 1633
Reputation: 9148
First, create custom view class
class CustomView: UIView {
// MARK: Custom View Initilization
var view: UIView!
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
addSubview(view)
//// additional setup here
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
// set nibName to be xib file's name
let nib = UINib(nibName: "CustomView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
}
Second, in CustomView.xib
set File's owner
custom class to CustomView
After, you've done. you can create the custom view programmatically.
let customView = CustomView(frame: frame)
self.view.addSubview(customView)
Or using storyboard, by drag UIView to ViewController and set UIView's custom class to CustomView
Upvotes: 3