当使用绑定和结构时,自定义nspopupbutton标题。

问题描述 投票:0回答:1

如何通过绑定来显示时区标识符(使用结构)? 例如,我想只显示Africaxxx偏移量3600,而不是Africaxxx。

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:用这个黑客可以做到,但它看起来很不迅速,我怕它将来会崩溃

extension NSTimeZone {

    open override func value(forKey key: String) -> Any? {
        if key == "description" {
            return self.name
        }
        return super.value(forKey: key)
    }
}
macos cocoa timezone cocoa-bindings nspopupbutton
1个回答
1
投票

绑定 contentValues

NSPopUpButton中显示为项目的字符串数组。

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

参见 NSPopUpButton Bindings.

© www.soinside.com 2019 - 2024. All rights reserved.