macos - 使用绑定(bind)和结构时自定义 nspopupbutton 标题

标签 macos cocoa timezone cocoa-bindings nspopupbutton

如何通过绑定(bind)(使用结构)显示时区标识符?例如而不是 Africa/xxx offset 3600 我只想要 Africa/xxx

class TimezonePopupButton: NSPopUpButton {

    private var timezonesController: NSArrayController = NSArrayController()

    private var timeZones : [TimeZone] = {
        var content : [TimeZone] = []
        for identifier in TimeZone.knownTimeZoneIdentifiers {
            if let timeZone = TimeZone(identifier: identifier) {
                content.append(timeZone)
            }
        }
        return content
    }()

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    func commonInit() {
        timezonesController.content = timeZones
        bind(.content, to: timezonesController, withKeyPath: "arrangedObjects")
        selectItem(withTitle: TimeZone.current.identifier)
    }
}

enter image description here

PS:可以用这个 hack 来完成,但它看起来非常不迅速,我担心它将来会崩溃

extension NSTimeZone {

    open override func value(forKey key: String) -> Any? {
        if key == "description" {
            return self.name
        }
        return super.value(forKey: key)
    }
}

最佳答案

绑定(bind)contentValues

An array of strings that are displayed as the items in the NSPopUpButton.

bind(.content, to: timezonesController, withKeyPath: "arrangedObjects")
bind(.contentValues, to: timezonesController, withKeyPath: "arrangedObjects.name")

参见NSPopUpButton Bindings .

关于macos - 使用绑定(bind)和结构时自定义 nspopupbutton 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61867780/

相关文章:

macos - 配置文件的默认位置 - MacOS?

c++ - 为什么 HID 在 mac 中枚举 Apple Internal Keyboard/Trackpad 3 次?

objective-c - 升级到 Xcode 5.0.2 : xib warning. 属性不可用

cocoa - NOOB 从代码中获取结果时出现问题(更具体地说是使用 NSComboBox)

mysql - 在 MySQL 中以美洲太平洋时区格式保存日期

macos - 如何在带有 SED 的 OS X 中不在末尾添加新行

cocoa - 我可以更改 NSScreen 可见框架吗?

iphone - 检查预编译时是否链接了框架

php - 乔姆拉!时区

timezone - 时刻 js 选择了错误的时区/偏移量,因此从 UTC 到本地时间的转换是不正确的