我想知道是否可以动态创建NSTouchBar项。在我的应用程序中,我有一个填充NSTableViewController内容的dataSource协议。我想使用这个协议来用相同的选项填充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
}
}
}有没有办法做我想做的事?
发布于 2018-09-04 15:29:35
NSTouchBarItem.Identifier可以基于任何字符串,包括基于Restaurant对象的某个标识符的动态字符串。您可以将defaultItemIdentifiers设置为动态生成的标识符的数组,然后将为每个标识符调用touchBar(_:,makeItemForIdentifier:) (然后您可以动态地为每个标识符创建一个按钮或其他方式)。
另一种选择是使用NSScrubber。这可以是Touch Bar中的单个项目,但是它有一个DataSource,可用于根据您的Restaurant数据源填充它。
https://stackoverflow.com/questions/52096989
复制相似问题