简体   繁体   中英

Timer setting not working in iOS

I have a problem with timer setting.

The code I wrote for it is:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: Selector(("updateTimer")), userInfo: nil, repeats: true)
    }

    func updateTimer(){
        label.text = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short)
    }
}

I run the app, and instead of timer I get an error of type Thread. Something like:

"Thread 1: signal SIGBART"

What could be the problem?

Things will work better if you replace Selector(("updateTimer")) with #selector(updateTimer) .

Then you'll be told you need to add @objc to your updateTimer function.

Unrelated but don't use NSDate .

Here's your fixed code:

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }

    @objc func updateTimer() {
        label.text = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
    }
}

Change your code to this:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}

@objc func updateTimer(){
    label.text = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short)
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM