I am trying to create a custom view in Swift by subclassing UIView , and I have a view pane named MyViewPanel.xib that has a class assigned by MyCustomView . The implementation is as follows:
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"
During runtime, I found the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Since awakeFromNib() is the first lifecycle event in UIView , I donβt understand why in this case the UILabel title is zero.
Edit:
To use this custom view, I simply draw a UIView rectangle on my storyboard and assign it to the MyCustomView class. In the viewDidLoad() method of my ViewController for the storyboard, I asked a question on a user view:
override func viewDidLoad() {
source share