gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:10 25 4
gpt4 key购买 nike

我目前正在尝试通过一本 Mac Apps 书籍学习 Cocoa,其中一个程序具有 windowShouldClose(_:) 委托(delegate)函数。但是,当我运行程序时,只要调用此函数,窗口仍会关闭。程序仍在运行,但窗口关闭。谁能解释为什么会这样?这是我的代码:

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
}
}

谢谢!

最佳答案

您需要将主视图 Controller 设置为 NSWindow 的委托(delegate)。

在您的 windowDidLoad 中,您可以将 self 设置为窗口的委托(delegate)

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

关于swift - windowShouldClose(_ :) delegate function not being called in code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com