我目前正在尝试通过一本 Mac Apps 书籍来学习 Cocoa,其中一个程序具有 windowShouldClose(_:) 委托函数。但是,当我运行该程序时,只要调用该函数,窗口仍然会关闭。程序仍在运行,但窗口关闭。谁能解释为什么会发生这种情况?这是我的代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
您需要将主视图控制器设置为 NSWindow 的委托。
在 windowDidLoad 中,您可以将 self 设置为窗口的委托
override func windowDidLoad() {
super.windowDidLoad()
updateButtons()
speechSynth.delegate = self
self.window.delegate = self
}
Run Code Online (Sandbox Code Playgroud)