Swift 无法以编程方式更新NSTouchBar
我目前正在开发一个非常简单的Live Scores MAC OSX应用程序,供个人使用,我在触摸栏上显示一组标签(分数)。我试图通过几个步骤实现的目标:Swift 无法以编程方式更新NSTouchBar,swift,macos,swift4,macos-mojave,nstouchbar,Swift,Macos,Swift4,Macos Mojave,Nstouchbar,我目前正在开发一个非常简单的Live Scores MAC OSX应用程序,供个人使用,我在触摸栏上显示一组标签(分数)。我试图通过几个步骤实现的目标: 每30秒从第三方API获取实时足球分数 解析分数并将其制成标签 用新分数更新触摸栏 [请注意,此应用程序不会在任何地方发布,只供个人使用。我知道,苹果严格建议不要在触摸栏中使用此类内容。] 下面是我在RW()的基本触摸栏教程中编写的代码。我的代码框架摘自RW教程: 在WindowController(情节提要入口点)中,按如下方式覆盖makeT
WindowController
(情节提要入口点)中,按如下方式覆盖makeTouchBar
:ViewController
中,它也是触摸栏代理,执行makeTouchBar
fn:nTouchBarDelegate
在ViewController
中<代码>分数是我存储获取分数的地方(请参见5)。如果尚未获取分数,则返回视图的nil
:fetchScores
函数,它还调用该函数来更新触摸栏:@objc func fetchScores(){
让url=“”
请求(url).responseJSON{response in
如果让json=response.result.value{
//在此处更新self.scores,并用最新分数填写
如果可用(OSX 10.12.2,*){
//self.touchBar=nil
self.touchBar=self.makeTouchBar()//这是我再次调用makeTouchBar来动态更新触摸栏内容的地方
}
}
}
我从上面的代码中了解到,一旦我在fetchScores
中调用makeTouchBar
,并将其分配给我的viewcontroller的touchBar
属性,理想情况下,它应该调用touchBar(:makeItemForIdentifier)
委托函数来更新触摸栏视图()。但在我的情况下,touchBar(:makeItemForIdentifier)
从未被调用。唯一调用触摸栏(:makeItemForIdentifier)
的时间是第一次,从我的WindowController调用makeTouchBar
时(见上文第1点)。由于尚未检索到分数,我的触摸栏仍然为空
override func makeTouchBar() -> NSTouchBar? {
guard let viewController = contentViewController as? ViewController else {
return nil
}
return viewController.makeTouchBar()
}
override func makeTouchBar() -> NSTouchBar? {
let touchBar = NSTouchBar()
touchBar.delegate = self
touchBar.customizationIdentifier = .scoresBar
touchBar.defaultItemIdentifiers = [.match1, .flexibleSpace, .match2, ... , .match10]
return touchBar
}
extension ViewController: NSTouchBarDelegate {
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
if (<scores not fetched yet>) {
return nil
}
// matchNum is the match number for which I am showing scores for
let customViewItem = NSCustomTouchBarItem(identifier: identifier)
customViewItem.view = NSTextField(labelWithString: self.scores[matchNum ?? 0])
return customViewItem
}
}
_ = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(ViewController.fetchScores), userInfo: nil, repeats: true)
@objc func fetchScores() {
let url = "<scores api end point>"
Alamofire.request(url).responseJSON { response in
if let json = response.result.value {
// update self.scores here and fill it with latest scores
if #available(OSX 10.12.2, *) {
//self.touchBar = nil
self.touchBar = self.makeTouchBar() // This is where I am calling makeTouchBar again to update Touch Bar content dynamically
}
}
}