IBOutlet属性在从xib加载的自定义视图后无n
问题描述:
IBOutlets发生了一些奇怪的事情。 IBOutlet属性在从xib加载的自定义视图后无n
在代码中,我尝试访问此属性,但它们是nil
。代码:
class CustomKeyboard: UIView {
@IBOutlet var aButt: UIButton!
@IBOutlet var oButt: UIButton!
class func keyboard() -> UIView {
let nib = UINib(nibName: "CustomKeyboard", bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as UIView
}
override init() {
super.init()
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Private
private func commonInit() {
println(aButt)
// aButt is nil
aButt = self.viewWithTag(1) as UIButton
println(aButt)
// aButt is not nil
}
}
答
这是预料之中的,因为IBOutlet在调用初始化程序时未分配。您不需要commonInit,只需重写awakeFromNib,如下所示:
override func awakeFromNib() {
super.awakeFromNib()
print(aButt)
}
答
您的笔尖可能未连接。我的解决方案非常简单。在你项目的某个地方(我创建了一个名为UIViewExtension.swift的类),用这个方便的connectNibUI方法添加UIView的扩展。
extension UIView {
func connectNibUI() {
let nib = UINib(nibName: String(describing: type(of: self)), bundle: nil).instantiate(withOwner: self, options: nil)
let nibView = nib.first as! UIView
nibView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(nibView)
//I am using SnapKit cocoapod for this method, to update constraints. You can use NSLayoutConstraints if you prefer.
nibView.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self)
}
}
}
现在你可以调用这个方法上的任何观点,在你的init方法,这样做:
override init(frame: CGRect) {
super.init(frame: frame)
connectNibUI()
}
+0
还要确保您的视图通过“文件所有者”进行连接。 – 2016-11-30 23:23:57
你在哪里访问它们除了commonInit? – 2015-02-07 17:34:27
@AshrafTawfeeq现在无处可去。我不能正常初始化这个类。 干净的项目也没有帮助 – Sk0prion 2015-02-07 18:17:11
在初始化时,Outlet尚未设置,因为视图尚未加载。您的第二个日志工作,因为访问视图导致它被加载。 – rdelmar 2015-02-07 18:18:13