我在一个类中创建了一个计时器,并尝试在计时器工作时在另一个类中做其他事情,并在计时器停止时做其他事情。例如,当计时器工作时显示每一秒。我将代码简化如下。如何实现这一点?
import Foundation
import UIView
class TimerCount {
var timer: NSTimer!
var time: Int!
init(){
time = 5
timer = NSTimer.scheduledTimerWithTimeInterval( 1.0 , target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update(){
if(time > 0) {
time = time - 1
// do something while timer works
}
else{
timer.invalidate()
timer = nil
time = 5
}
}
}
class Main: UIView {
var Clock: TimerCount!
override func viewDidLoad() {
Clock = TimerCount()
//? do something else while clock works
// ? do other things while clock stops
// FOR EXAMPLE: show every second when timer works
if(Clock.time > 0){
println(Clock.time)
}else{
println("clocker stops")
}
}
}发布于 2014-07-05 04:06:23
viewDidLoad很可能只会被调用一次。您可以简单地将更新方法放在Main对象中,然后将main的实例和更新方法传递给scheduledTimerWithTimerInterval调用。否则,您需要在主类中使用一个新方法来从timerCount类调用,并传入当前时间的int。
这是在你的主类中:
func updateMethodInMain(timeAsInt: Int){
//do stuff in Main instance based on timeAsInt
}以下是您在timer类中拥有的内容:
func update(){
if(time > 0) {
time = time - 1
instanceNameForMain.updateMethodInMain(time)
}
else{
timer.invalidate()
timer = nil
time = 5
}
}
}https://stackoverflow.com/questions/24577956
复制相似问题