是否可以刷新Today Widget中的计时器?

问题描述 投票:6回答:2

我想知道是否可以在今天的小部件中更新计时器的文本标签。我环顾四周但没有帮助我。

ios swift timer ios8-today-widget today-extension
2个回答
7
投票

是的你可以。我刚刚测试过它的确有效。您只需将计时器添加到主运行循环NSRunLoopCommonModes:

RunLoop.main.add(yourTimerName, forMode: .commonModes)

import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding {

    @IBOutlet weak var strTimer: UILabel!

    var timer = Timer()

    func updateInfo() {
        strTimer.text = Date().description
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateInfo), userInfo: nil, repeats: true)
        RunLoop.main.add(timer, forMode: .commonModes)
    }
    func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) {
        completionHandler(.newData)
    }
}

3
投票

我知道这是一个Swift问题,但我发现它寻找Objective-C代码,所以其他人也可能。

-(void) viewDidLoad
{
    [NSTimer scheduledTimerWithTimeInterval:1 // update more than once a second to appear in sync with the system clock
                                     target:self
                                   selector:@selector(updateUi:)
                                   userInfo:nil
                                    repeats:YES];

}


-(void) updateUi:(NSTimer *)timer 
{
   // Update Widget UI as required
}
© www.soinside.com 2019 - 2024. All rights reserved.