计时器功能崩溃应用程序

时间:2018-02-17 14:28:06

标签: swift crash

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!
var timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.runTimedCode), userInfo: nil, repeats: true)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@objc func runTimedCode() {

  imageView.image = UIImage(named: "card10")
}

}

此代码向我提供消息“无法识别的选择器发送到实例”但我不知道问题是什么。有人可以帮帮我吗? :)

2 个答案:

答案 0 :(得分:0)

你必须像下面这样调用函数。

 var timer:Timer?

    override func viewDidLoad(){
    super.viewDidLoad()

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

     @objc func runTimedCode(){

print("timer is calling")
  }       

答案 1 :(得分:0)

请改为尝试:

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    var timer: Timer? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.runTimedCode), userInfo: nil, repeats: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @objc func runTimedCode() {

        imageView.image = UIImage(named: "card10")
    }
}