This is my first time working with custom view and I'm so confused as to how to proceed.
I have a custom view, inherited from NSView
with just 3 things on it: an image view, and 2 text fields:
// MyCustomView.swift
import Cocoa
@IBDesignable class MyCustomView: NSView {
@IBOutlet weak var imageView: NSImageView!
@IBOutlet weak var titleField: NSTextField!
@IBOutlet weak var subtitleField: NSTextField!
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
}
I added a XIB file, designed the view and connected all the outlets:
Now my main storyboard I added a generic view, change its class to MyCustomView
and connected the outlet. Here's the code for ViewController.swift
:
// ViewController.swift
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var customView: MyCustomView!
override func viewDidLoad() {
super.viewDidLoad()
customView.titleField.stringValue = "This is a title"
}
}
At run time I got a fatal error on the customeView.titleField.stringValue = ...
line:
fatal error: unexpectedly found nil while unwrapping an Optional value
If I take out that line, the app compiles but the custom view is blank.
So I guess my custom design did not carry over from MyCustomView.xib
? How can I correct that? I double checked and all the outlets are connected in IB.