由于 macOS Sonoma 上的错误,我正在寻找一种解决方法来在沙盒应用程序中触发
NSSavePanel
的默认操作。
问题是
NSSavePanel
的 accessorryView
视图对输入按键没有反应。这适用于较低的 macOS 版本。
按 Enter 键会调用
performKeyEquivalent:
链中的 NSResponder
。
我可以在沙盒应用程序中调用
savePanel.performKeyEquivalent
就到此为止吗?
import Carbon.HIToolbox.Events
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if let savePanel, event.type == .keyDown && (event.keyCode == UInt16(kVK_Return) || event.keyCode == UInt16(kVK_ANSI_KeypadEnter)) {
savePanel.performKeyEquivalent(with: event)
} else {
super.performKeyEquivalent(with: event)
}
}
PS:Ventura 及以下版本不需要此解决方法
完整的快速示例:
import Carbon.HIToolbox.Events
class CustomView: NSView {
weak var savePanel: NSSavePanel?
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if let savePanel, event.type == .keyDown && (event.keyCode == UInt16(kVK_Return) || event.keyCode == UInt16(kVK_ANSI_KeypadEnter)) {
savePanel.performKeyEquivalent(with: event)
} else {
super.performKeyEquivalent(with: event)
}
}
}
class ViewController: NSViewController {
let savePanel = NSSavePanel()
override func viewDidLoad() {
super.viewDidLoad()
let customView = CustomView()
customView.addSubview(NSTextField(string: "11111111"))
customView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customView.widthAnchor.constraint(equalToConstant: 120),
customView.heightAnchor.constraint(equalToConstant: 20)
])
customView.savePanel = savePanel
savePanel.accessoryView = customView
}
override func viewWillAppear() {
savePanel.runModal()
}
}
这是 macOS14 上的一个错误。已在 macOS15 中修复。提供的代码可在生产应用程序中运行。
import Carbon.HIToolbox.Events
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if let savePanel, event.type == .keyDown && (event.keyCode == UInt16(kVK_Return) || event.keyCode == UInt16(kVK_ANSI_KeypadEnter)) {
savePanel.performKeyEquivalent(with: event)
} else {
super.performKeyEquivalent(with: event)
}
}