我正在练习awakeFromNib。
我在Main.storyboard中只有一个UIView
。
此UIView继承class CardView
。
代码在
下方class ViewController: UIViewController {
@IBOutlet weak var cardView: CardView!
}
我有一个CardView.xib
。在CardView.xib中,有一个默认的UIView继承了class CardView
。在此UIView中,还有另一个继承了class CardContentView
的单一视图。
当然,我有一个CardView.swift,其中有class CardView
。
代码在下面
class CardView: UIView {
@IBOutlet weak var cardContentView: CardContentView!
override func awakeFromNib() {
cardContentView.layer.cornerRadius = 16
}
}
我有一个CardContentView.xib
。在CardContentView.xib中,有一个默认的UIView
,它继承了默认的class UIView
。
当然,我有一个CardContentView.swift,其中有class CardContentView
。
代码在下面
class CardContentView: UIView {
@IBOutlet var backgroundView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit(){
Bundle.main.loadNibNamed("CardContentView", owner: self, options: nil)
self.addSubview(backgroundView)
}
}
是的,我想通过CardContentView
在ViewController中将cardView
显示为class CardView
。
但是当我运行时,错误会弹出class CardView
错误行在func awakeFromNib
特定行为cardContentView.layer.cornerRadius = 16
。
错误消息为Unexpectedly found nil while unwrapping an Optional value
。特别是cardContentView = nil
。
我不知道为什么cardContentView = nil
。
我将Xib板中的cardContentView链接到CardView.swift中的class CardView
。
我应该如何修改代码来运行它?
谢谢!
答案 0 :(得分:0)
首先,您需要在主故事板上连接cardView插座,当然,您已经在ViewController中添加了一个视图。然后,在CardView类中,您必须实例化cardContentView出口,因为在CardView.xib中您没有对cardContentView的任何引用。确保已连接CardContentView.xib中的backgroundView插座。
class CardView: UIView {
@IBOutlet weak var cardContentView: CardContentView!
override func awakeFromNib() {
super.awakeFromNib()
cardContentView = Bundle.main.loadNibNamed("CardContentView", owner: self, options: nil)!.first as! CardContentView
self.addSubview(cardContentView)
cardContentView.layer.cornerRadius = 16
//you can also get access to the subviews of cardContentView
//cardContentView.backgroundView.backgroundColor = .red
}
}
class CardContentView: UIView {
@IBOutlet var backgroundView: UIView!
override func awakeFromNib() {
backgroundView.backgroundColor = .yellow
}
override init(frame: CGRect) {
super.init(frame: frame)
//commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//commonInit()
}
private func commonInit() {
}
}