windowShouldClose(_:) delegate function not being called in code

Viewed 1776

I am currently trying to learn Cocoa through a Mac Apps book and one of the programs has the windowShouldClose(_:) delegate function. However, when I run the program, the window will still close whenever this function is supposed to be called. The program still runs, but the window closes. Can anyone explain why this happens? Here is my code:

import Cocoa

class MainWindowController: NSWindowController, NSSpeechSynthesizerDelegate, NSWindowDelegate {

@IBOutlet weak var textField: NSTextField!
@IBOutlet weak var speakButton: NSButton!
@IBOutlet weak var stopButton: NSButton!

let speechSynth = NSSpeechSynthesizer()

var isStarted: Bool = false {
    didSet {
        updateButtons()
    }
    }

override var windowNibName: String {
    return "MainWindowController"
}

override func windowDidLoad() {
    super.windowDidLoad()
    updateButtons()
    speechSynth.delegate = self
}

//MARK: - Action methods

//get typed-in text as string
@IBAction func speakIt(sender: NSButton){
    let string = textField.stringValue
    if string.isEmpty {
        print("string from \(textField) is empty")
    } else{
        speechSynth.startSpeakingString(string)
        isStarted = true
        }

    }
@IBAction func stopIt(sender: NSButton){
    speechSynth.stopSpeaking()
}

func updateButtons(){
    if isStarted{
        speakButton.enabled = false
        stopButton.enabled = true
    } else {
        speakButton.enabled = true
        stopButton.enabled = false
    }
}

//Mark: NSSpeechSynthDelegate
func speechSynthesizer(sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool){
    isStarted = false
    print("finished speaking=\(finishedSpeaking)")
}

//Mark: Window Delegate
func windowShouldClose(sender: AnyObject) -> Bool {
    return !isStarted
}
}

Thanks!

4 Answers

What Shripada said is correct, but there's also another catch. Don't forget to make a connection from your MainWindowController to the window defined in your xib, otherwise the window outlet won't be referencing anything.

So, the window defined in your File's ownerenter image description here

should reference the window in interface builder enter image description here

windowShouldClose() was not being called in my code either after upgrading to Swift 5. In previous versions, it was sufficient to have the app delegate inherit from NSApplicationDelegate for it to receive the windowShouldClose() notification (building in Xcode). Upgrading to Swift 5, I had to have my app delegate also inherit from NSWindowDelegate to get the notification. This declaration restored the window close notification to my app:

class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {

your method signature has to match exactly. it has to be

windowShouldClose(_:)

the _ is important.

Related