【问题标题】:Custom nspopupbutton title when using bindings and struct使用绑定和结构时自定义 nspopupbutton 标题
【发布时间】:2020-05-18 10:42:45
【问题描述】:

如何通过绑定(使用结构)显示时区标识符?例如而不是 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)
    }
}

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

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】:

    绑定contentValues

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

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

    NSPopUpButton Bindings

    【讨论】:

    • 只是一个问题。这是有效的,因为 objc 运行时是 NSTimezone 并因此响应名称。当 swift TimeZone 使用“标识符”(目前它崩溃)时,它是未来的证明吗?
    • 对不起,我不明白这个问题。
    • 我的错。意味着绑定使用 struct TimeZone;此结构没有“名称”作为属性/变量。它起作用的原因是因为 struct TimeZone 在引擎盖下 NSTimeZone 具有一个名为“name”的属性。作为 objc dev 我期望“标识符”变量是可绑定的(不是)。我只是担心这段代码会随着新版本的 macOS 或 swift 崩溃
    • 我认为name 属性与使用TimeZoneNSArrayController 和绑定一样具有前瞻性。
    猜你喜欢
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多