【发布时间】:2016-01-09 23:16:56
【问题描述】:
我正在尝试通过子类化UIView 在 Swift 中创建自定义视图,并且我有一个名为 MyViewPanel.xib 的视图板,它的类分配给了 MyCustomView。实现如下:
import UIKit
@IBDesignable
class MyCustomView: UIView {
@IBOutlet weak var title: UILabel!
var question: Question {
didSet {
print("did set question, title is: \(question.title)")
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
let height = rect.height
let width = rect.width
let color: UIColor = UIColor.whiteColor()
let drect = CGRect(x: (width * 0.25), y: (height * 0.25), width: (width * 0.5),height: (height * 0.5))
let bpath: UIBezierPath = UIBezierPath(rect: drect)
color.set()
bpath.stroke()
}
override func awakeFromNib() {
super.awakeFromNib()
print("awake from nib!")
self.title.text = "Test title" // error: found nil while unwrapping an Optional Value
}
}
在运行过程中,遇到如下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
由于awakeFromNib() 是UIView 中的第一个生命周期事件,我不明白为什么title UILabel 在这种情况下为零。
编辑:
要使用这个自定义视图,我只需在我的故事板上绘制一个UIView 矩形并将其类分配给MyCustomView。在我的故事板ViewController 的viewDidLoad() 方法中,我在自定义视图上设置了问题:
override func viewDidLoad() {
// myCustomView is an IBOutlet in the view controller
myCustomView.question = question
}
【问题讨论】:
-
如何创建视图实例?
-
我只是在我的故事板上画了一个
UIView矩形并将其类分配给MyCustomView。这是错的吗?谢谢 -
那么你找到这个问题的答案了吗?
-
@TonyGW,这是正确的。你有没有最终找到一个不涉及 UIViewController 的问题的解决方案?我想做一个通用的 UIView 对视图控制器没有任何意见。很好的问题。如果可以的话,我会再次投票。