[英]Loading view from XIB into ViewController and VIewCell
I have a XIB with a custom class ProfileHeaderView . 我有一个带有自定义类ProfileHeaderView的XIB。 I also have ProfileViewController and ProfileTableViewCell , both with IBOutlet profileHeader . 我也有ProfileViewController和ProfileTableViewCell ,它们都具有IBOutlet profileHeader 。
What I want is to load nib into profileHeader . 我想要的是将笔尖加载到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. 到目前为止,我是通过加载NIB然后将其添加为profileHeader的子视图来实现的 ,我认为这不是最佳解决方案,因此我必须手动设置框架。
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
其次,在CustomView.xib
中将File's owner
自定义类设置为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
或使用情节CustomView
,通过将UIView拖到ViewController并将UIView的自定义类设置为CustomView
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.