我正在练习清醒。
我在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)
}
}
是的,我想通过class CardView
在ViewController中显示要cardView
CardContentView
。
但是当我运行时,错误弹出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
。
我应该如何修改代码来运行它?
谢谢!
首先,您需要在主情节提要中连接 cardView 插座,当然,您已经在 ViewController 中添加了一个视图。然后在 CardView 类中,您必须实例化 cardContentView outlet,因为在 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() {
}
}