如何在 Swift 的自定义类中初始化 Timer? [英] How initialize a Timer inside a custom class in Swift?

查看:40
本文介绍了如何在 Swift 的自定义类中初始化 Timer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个简单的 cronometer 应用程序,但是,现在我想让它变得更好,我想为 cronometer 控件编写一个类:

I make a simple cronometer app, but, now I want make it better, and I would like to write a class for the cronometer control:

class Cronometer{
    private var counter:Int = 0
    private var timer:Timer = Timer()
    private var state:Bool = true

   func initCronometer(){
        if self.state{
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector("onTick"), userInfo: nil, repeats: true)
        }else{
            self.timer.invalidate()
        }
        self.state = !self.state
    }

    func onTick(){
        self.counter += 1
        print(self.counter)
    }
}

但是选择器参数在具有自定义方法的类中不起作用.我不希望它在 ViewController 中,就像我之前所做的那样.

But the selector parameter it's not working inside the class with a custom method. I don't want it inside the ViewController, like as I maded before.

我试试

self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector(("onTick")), userInfo: nil, repeats: true)

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

...但还是不行

那么,在 Timer 初始值设定项中将类方法指定为选择器的最佳方法是什么?

So, whats it's the best way to assign a class method as selector in the Timer initializer?

非常感谢!

推荐答案

Timer 是 Foundation 类型 NSTimer 的覆盖类型,它使用 Objective-C 消息传递来调用计时器目标.因此,目标方法必须可用于 Objective-C.

Timer is an overlay type for the Foundation type NSTimer, which uses Objective-C messaging to invoke the timer target. Therefore the target method must be available for use in Objective-C.

您有以下选择:

  • 只用 @objc 标记 onTick() 方法(正如 Matt 已经说过的).
  • 使 Cronometer 类成为 NSObject 的子类.
  • 在 iOS 10/macOS 10.12 上,您可以使用更新的基于块的计时器 API:

  • Mark only the onTick() method with @objc (as Matt already said).
  • Make the Cronometer class a subclass of NSObject.
  • On iOS 10/macOS 10.12 you can use the newer block-based timer API:

self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
   _ in self.onTick()
}

这篇关于如何在 Swift 的自定义类中初始化 Timer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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