[英]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.