[英]Link a UIView subclass to xib file
我創建了一個UIView
子類,我想將其鏈接到xib文件。 我添加了一個xib文件,並將該類設置為DraggableView,但是例如當我創建一個標簽並將其鏈接到information
。 它返回的information
等於零? 為什么不起作用?
class DraggableView: UIView {
var delegate: DraggableViewDelegate!
@IBOutlet var information: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
information.text = "no info given"
information.textAlignment = NSTextAlignment.Center
information.textColor = UIColor.blackColor()
self.backgroundColor = UIColor.whiteColor()
}
}
請確保像這樣在自定義UIView中從XIB方法添加init:
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
然后您可以像這樣使用它:
var view = DraggableView.instanceFromNib()
view.information.text = "Test Label"
self.view.addSubview(view)
在設置對象值之前,您需要自定義UIView首先加載XIB文件。
class DraggableView: UIView {
var delegate: DraggableViewDelegate!
@IBOutlet var information: UILabel!
init() { xibSetup() }
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if self.subviews.count == 0 {
xibSetup()
}
}
func xibSetup() {
let view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
// INIT THERE YOUR LABEL
information.text = "no info given"
information.textAlignment = NSTextAlignment.Center
information.textColor = UIColor.blackColor()
self.backgroundColor = UIColor.whiteColor()
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "nib file name", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
然后簡單地這樣調用:
var view = DraggableView()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.