我正在Mac OS的“首选项”窗口上工作,即使工具栏项被标记为“可选”,并且委托方法返回的工具栏的标识符仍为“ AllowedItemIdentifiers”和“ toolbarSelectableItemIdentifiers”,按钮仍然无法选择。
如果我在viewDidLoad中以编程方式启用(破解),它将立即恢复为禁用状态。
故事板:
对应的班级:
class PreferenceWindowController: NSWindowController, NSToolbarDelegate {
@IBOutlet weak var toolbar: NSToolbar!
enum Identifier: String, Equatable {
case General = "General"
case Network = "Network"
case Advanced = "Advanced"
static let allValuesRaw = [General.rawValue, Network.rawValue]//, Advanced.rawValue]
static let allValues = [General.toolbarId, Network.toolbarId]//, Advanced.toolbarId]
var toolbarId: NSToolbarItem.Identifier {
return NSToolbarItem.Identifier(rawValue: self.rawValue)
}
}
override func windowDidLoad() {
super.windowDidLoad()
self.toolbar.selectedItemIdentifier = NSToolbarItem.Identifier(rawValue: Identifier.General.rawValue)
self.window!.contentViewController = NSStoryboard(name: "Preference", bundle: nil).instantiateController(withIdentifier: "GeneralViewController") as! GeneralViewController
}
@IBAction func selectedItem(_ sender: NSToolbarItem) {
switch sender.itemIdentifier.rawValue {
case Identifier.General.rawValue:
self.window!.contentViewController = NSStoryboard(name: "Preference", bundle: nil).instantiateController(withIdentifier: "GeneralViewController") as! GeneralViewController
case Identifier.Network.rawValue:
self.window!.contentViewController = NSStoryboard(name: "Preference", bundle: nil).instantiateController(withIdentifier: "NetworkViewController") as! WebhooksViewController
case Identifier.Advanced.rawValue:
self.window!.contentViewController = NSStoryboard(name: "Preference", bundle: nil).instantiateController(withIdentifier: "AdvancedViewController") as! AdvancedViewController
default:
self.window!.contentViewController = NSStoryboard(name: "Preference", bundle: nil).instantiateController(withIdentifier: "GeneralViewController") as! GeneralViewController
}
}
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
return Identifier.allValues
}
private func toolbarSelectableItemIdentifiers(_ toolbar: NSToolbar) -> [String] {
return Identifier.allValuesRaw
}
}
更新:
我已禁用自动验证,并且已将所有NSToolbarItems更改为CustomToolbarItem类,但从未调用过validate。奇怪的是,第一个按钮(常规)有效,而第二个按钮(网络)无效。我已经在具有相同问题的新项目中尝试过(仅第一项有效)。
class CustomToolbarItem: NSToolbarItem {
override func validate() {
// validate content view
if
let control = self.view as? NSControl,
let action = self.action,
let validator = NSApp.target(forAction: action, to: self.target, from: self) as AnyObject?
{
switch validator {
case let validator as NSUserInterfaceValidations:
control.isEnabled = validator.validateUserInterfaceItem(self)
default:
control.isEnabled = validator.validateToolbarItem(self)
}
} else {
super.validate()
}
}