Search code examples
swiftinstancemousedownnsdatepicker

Subclass of NSDatePicker mouseDown event changes datePicker instance


I have instantiated and initialized a subclass of NSDatePicker in AppDelegate -> applicationDidFinishLaunching and overrode mouseDown(with event: NSEvent)in the datePicker subclass. When I press the mouse button in the datePicker and break in its overridden mouseDown func the instance is not the one I instantiated in applicationDidFinishLaunching and so is not initialized.

I've tried creating the instance at different entry points thinking it might be a timing thing but I've gotten nowhere. I'm out of ideas and feeling a little feeble. Any Help?

The datePicker:

import Cocoa

class AlarmIVDatePicker: NSDatePicker {
    var viewController: ViewController!

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }
    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        return true
    }
    override func mouseDown(with event: NSEvent) {
        let stop = 0
    }
}

The ViewController:

class ViewController: NSViewController, NSWindowDelegate{

var alarmIVDatePicker: AlarmIVDatePicker!


override func viewDidLoad() {
    super.viewDidLoad()

    alarmIVDatePicker = AlarmIVDatePicker()
    alarmIVDatePicker.viewController = self


}

I expected I could access the values I had set but the instance is not the one I created and all the values are nil


Solution

  • Okay. Here's what you can do to track this down. Add this code to your AlarmIVDatePicker class:

    override init(frame frameRect: NSRect) {
        Swift.print("AlarmIVDatePicker being called here")
        super.init(frame: frameRect)
    }
    
    convenience init() {
        self.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        Swift.print("hey, you DID drop this into a storyboard or XIB file!")
        super.init(coder: coder)
    }
    

    If you set breakpoints inside these init methods, you'll catch when and where they are being called where you did not expect.