[英]Loading a custom UIView from a XIB file within a XIB for a ViewController view
[英]Loading view from XIB into ViewController and VIewCell
. 我有一个带有自定义类的XIB。 and , both with . 我也有和 ,它们都具有 。
. 我想要的是将笔尖加载到 。 which I guess is not the best solution and i have to set frame manually. 到目前为止,我是通过加载NIB然后将其添加为的子视图来 ,我认为这不是最佳解决方案,因此我必须手动设置框架。
let view = NSBundle.mainBundle().loadNibNamed("ProfileHeaderView", owner: self, options: nil).last as! ProfileHeaderView
view.setFrame(...)
self.profileHeaderView.addSubview(self.view)
最好的方法是什么?
首先,创建自定义视图类
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()
}
}
其次,在CustomView.xib
中将File's owner
自定义类设置为CustomView
之后,您就完成了。 您可以通过编程方式创建自定义视图。
let customView = CustomView(frame: frame)
self.view.addSubview(customView)
或使用情节CustomView
,通过将UIView拖到ViewController并将UIView的自定义类设置为CustomView
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.