【问题标题】:Dynamic NSTouchBar items动态 NSTouchBar 项目
【发布时间】:2018-09-04 15:29:34
【问题描述】:

我想知道是否可以动态创建NSTouchBar 项目。在我的应用程序中,我有一个 dataSource 协议来填充 NSTableViewController 的内容。我想使用这个协议也用相同的选项填充 touchBar。

这是我正在使用的协议。

protocol RestaurantsViewControllerDelegate {
    func numberOfRestaurants(in restaurantsViewController: RestaurantsViewController) -> Int
    func restaurantsViewController(_ restaurantsViewController: RestaurantsViewController, restaurantAtIndex index: Int) -> Restaurant
    func restaurantsViewController(_ restaurantsViewController: RestaurantsViewController, didSelectRestaurant restaurant: Restaurant)
}

不过,我发现的唯一代码表明我必须手动创建每个按钮,就像这样。

@available(OSX 10.12.1, *)
extension NSTouchBarItem.Identifier {
    static let restaurant = NSTouchBarItem.Identifier("my.custom.identifier")
}

extension RestaurantsViewController: NSTouchBarDelegate {
    override func makeTouchBar() -> NSTouchBar? {
        let touchBar = NSTouchBar()
        touchBar.delegate = self
        touchBar.defaultItemIdentifiers = [.restaurant]
        return touchBar
    }

    func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
        switch identifier {

        case NSTouchBarItem.Identifier.restaurant:
            let item = NSCustomTouchBarItem(identifier: identifier)
            item.view = NSButton(title: "This is a restaurant", target: nil, action: nil)
            return item
        default: return nil
        }
    }
}

有什么方法可以实现我想做的吗?

【问题讨论】:

    标签: swift appkit nstouchbar


    【解决方案1】:

    NSTouchBarItem.Identifier 可以基于任何字符串,包括基于Restaurant 对象的某些标识符的动态字符串。您可以将defaultItemIdentifiers 设置为动态生成的标识符数组,然后将为每个标识符调用touchBar(_:,makeItemForIdentifier:)(然后您可以为每个标识符动态创建一个按钮或其他方式)。

    另一种选择是使用NSScrubber。这可能是 Touch Bar 中的单个项目,但它有一个 DataSource,可用于根据您的 Restaurant 数据源填充它。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 2021-01-17
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多