我很确定@IBOutlet
之后super.awakeFromNib()
被初始化了,但它是零?
重现的步骤:
@IBOutlet
更新:
如果您直接使用Storyboard,这确实有效。
@IBOutlet
这样做。
import UIKit
class MyView: UIView {
@IBOutlet weak var myLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.myLabel.text = "Hello world"
}
override func didMoveToSuperview() {
self.myLabel.text = "Hello world"
}
override func layoutSubviews() {
self.myLabel.text = "Hello world"
}
override func didMoveToWindow() {
self.myLabel.text = "Hello world"
}
}
答案 0 :(得分:2)
Storyboard不会加载xib。您必须在视图中明确加载xib。故事板使用init(coder:)
:
func loadNib() -> UIView? {
guard
let nibName = NSStringFromClass(type(of: self)).components(separatedBy: ".").last,
let bundle = Bundle(for: type(of: self))
let views = bundle.loadNibNamed(nibName, owner: self, options: nil),
let contentView = views.first as? UIView
else {
return nil
}
return contentView
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let contentView = self.loadNib()!
self.addSubview(contentView)
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.frame = self.bounds
}
这将加载xib的根视图,将其添加到视图中。由于我们将self
作为所有者,因此网点将被连接。