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!

