1

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:

MyCustomView.xib

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.

Jenny
  • 2,041
  • 13
  • 15
  • Why do you need to subclass NSView when in fact you can access those controls by wiring them with the view controller? – El Tomato Aug 05 '17 at 22:56
  • The actual custom view is more complex. This is a simplified example – Jenny Aug 06 '17 at 02:22
  • This is not a duplicate of that question. i know what the error means but I'm asking how to set up my view and Interface Builder to avoid the error. – Jenny Aug 06 '17 at 15:49
  • Have you checked that neither `customView` nor `customView.titleField` is `nil`? – clemens Aug 07 '17 at 04:55
  • Did you consider the IB lifecycle? I mean, have you tried to put your code in awakeFromNib or something like that? This really seems like a lifecycle issue, probably because the IBOutlet is not instantiated yet, since it is optional and you're using forced unwrap... – henrique Aug 29 '17 at 18:23

1 Answers1

0
  1. Is your class in the Identity Inspector for the UIView MyCustomView?
  2. Is the IBOutlet link set correctly as a MyCustomView? (your storyboard side)
  3. Is the file owner for the XIB set to MyCustomView?
  4. Do you have initialisers for MyCustomView? ( override init(frame: CGRect) or required init?(coder aDecoder: NSCoder) )
axelspark
  • 198
  • 10