swift 上的计时器不起作用 [英] Timer on swift not working

查看:47
本文介绍了swift 上的计时器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用按钮的功能:

I have a function working with a button:

@IBAction func btnSiguiente(_ sender: Any) {
    if indexImagenes == imagenes.count {
        indexImagenes = 0
    }
    escaparate.image = NSImage(named: imagenes[indexImagenes])
    indexImagenes += 1
}

我想让它与计时器一起工作:

I want to make it work with a Timer:

 var playTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true)


func autoplay() {
    if indexImagenes == imagenes.count {
        indexImagenes = 0
    }
    escaparate.image = NSImage(named: imagenes[indexImagenes])
    indexImagenes += 1
}

但我在控制台中得到了这个:
[_SwiftValue 自动播放]:无法识别的选择器发送到实例 0x6080000451c0

But I get this in console:
[_SwiftValue autoplay]: unrecognized selector sent to instance 0x6080000451c0

推荐答案

要解决此问题,请在您所在的类的实例完全初始化后初始化计时器.

To fix this, initialize the timer once the instance of the class your are in is fully initialized.

所以只需给 var playTimer 一个默认值,如下所示:

So just give the var playTimer a default value as follows:

var playerTimer:Timer? = nil

然后在self"完全初始化后调用的某个函数中初始化计时器(例如 viewDidLoad(),假设此代码在 viewController 中):

Then initialize the timer in some function that gets called once 'self' is fully initialized (like viewDidLoad() for example, assuming this code is in a viewController):

override func viewDidLoad()
{
    super.viewDidLoad()
    playerTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true)
}

本质上,在向它发送选择器以执行之前,请确保self"已完全初始化.

Essentially just make sure 'self' is fully initialized before you send it a selector to perform.

这篇关于swift 上的计时器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆