类型'UIViewController'没有成员updateTimer

问题描述 投票:-6回答:3

我正在尝试访问UIViewController中的计时器属性

对于最新版本的swift UIViewController似乎没有成员“updateTimer”

class InGameViewController: UIViewController {

    @IBOutlet weak var countdownTimerLabel: UILabel!
    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var pointsLabel: UILabel!

    @IBOutlet weak var initialCountdownLabel: UILabel!

    var seconds = 5 
    var timer = Timer()
    var isTimerRunning = false 

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")

         }

    func runTimer() {

        timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(UIViewController.updateTimer)), userInfo: nil, repeats: true)
    }
}
swift
3个回答
0
投票

您需要首先创建一个updateTimer函数,以便在scheduledTimer函数的selector函数中使用。确保你把它装饰成objc。

还要在选择器函数中删除UIViewController,因为该函数仅出现在您当前的viewcontroller类(InGameViewController)中,而不是父UIViewController类。

    @objc func updateTimer() {
             print("timer updated")
    }

    timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(updateTimer)), userInfo: nil, repeats: true)

0
投票

UIViewController没有名为updateTimer的属性

我不认为你可以在#selector()中调用一个属性,因为它有错误的签名并且会失败。

供您参考的API参考:https://developer.apple.com/documentation/foundation/timer/1412416-scheduledtimer


0
投票
class InGameViewController: UIViewController {

    @IBOutlet weak var countdownTimerLabel: UILabel!
    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var pointsLabel: UILabel!

    @IBOutlet weak var initialCountdownLabel: UILabel!

    var seconds = 5 
    var timer = Timer()
    var isTimerRunning = false 

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")

         }

    func runTimer() {

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

@objc func updateTimer() {
             print("timer updated")
    }
© www.soinside.com 2019 - 2024. All rights reserved.