使用 cocoa 绑定(bind),我希望根据是否选中复选框来启用或禁用弹出按钮。
我以编程方式将复选框和弹出窗口添加到堆栈 View 中,如下所示:
private func addCheckBoxes() {
for period in String.BuildTimePeriod.allCases {
let checkbox = NSButton(checkboxWithTitle: period.rawValue.capitalized, target: self, action: nil)
checkbox.bind(.value, to: NSUserDefaultsController.shared, withKeyPath: "values.\(period.defaultsBoolKey.rawValue)", options: [NSBindingOption.continuouslyUpdatesValue: true])
stackView.addArrangedSubview(checkbox)
addPopUpToCheckbox(checkbox, period: period)
}
}
private func addPopUpToCheckbox(_ checkbox: NSButton, period: String.BuildTimePeriod) {
let popUp = NSPopUpButton(frame: checkbox.frame, pullsDown: false)
let timeBlocks = String.TimeBlock.allCases.map() { $0.rawValue.capitalized }
popUp.addItems(withTitles: timeBlocks)
popUp.bind(.selectedValue, to: NSUserDefaultsController.shared, withKeyPath: "values.\(period.rawValue)", options: [NSBindingOption.continuouslyUpdatesValue: true])
popUp.bind(.enabled, to: checkbox, withKeyPath: "state", options: [NSBindingOption.continuouslyUpdatesValue : true])
stackView.addArrangedSubview(popUp)
}
绑定(bind)在 Controller 的初始加载时起作用,但是,弹出窗口启用状态不会动态更改。想知道是否有人可以提供任何指导。
最佳答案
感谢@Willeke,我意识到这是因为我只是引用了“state”
,而不是按钮所需的“cell.state”
。
关于swift - 尝试将 NSPopupButton 的 `` `enabled ``` 属性绑定(bind)到复选框的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56973363/