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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.