我如何向IBOutlet添加重置功能,当前单击按钮然后定时器将启动,再次单击相同的按钮时它将停止,但是当第三次单击时它将再次启动,但我希望它重置。
@IBAction func start(sender: AnyObject) {
if !timer.valid{
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
stoptimer.text = String(arc4random_uniform(4)+1)
}
else{
timer.invalidate()
}
}
答案 0 :(得分:1)
为什么不在全局变量中保存按钮状态,这样你可以做你想做的事情?
这是一个简单的例子:(你也可以在这里获得按钮的标题)
var buttonState:Int = 0;
// func for buttonpress
@IBAction func startButtonClicked(sender: UIButton) {
switch(buttonState) {
case 0:
// button first pressed, run code
// set state to 1:
buttonState = 1;
break;
case 1:
// button second tap, run code
// set state to 2:
buttonState = 2;
break;
case 2:
// button third tap, run code
// reset state to 0:
buttonState = 0;
break;
....
答案 1 :(得分:1)
您可以为它设置一个bool,如下面的代码所示:
string finalStr;
foreach(var v in Messages)
{
finalStr += v + "\n";
}
return finalStr;
当您的计时器运行时单击开始按钮时,它将进入else并将var stopTime = false
@IBAction func start(sender: AnyObject) {
if !timer.valid && !stopTime{
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: aSelector, userInfo: nil, repeats: true)
var startTime = NSDate.timeIntervalSinceReferenceDate()
stoptimer.text = String(arc4random_uniform(4)+1)
}else if stopTime{
//reset you timer here
//reset your bool as per your need.
println("Reset")
} else {
stopTime = true
timer.invalidate()
}
}
bool设置为stopTime
,以便下次按下开始按钮时它将不会进入条件因为true
这次是stopTime
。
答案 2 :(得分:0)
或没有布尔
在您的班级中,将您的计时器声明为可选
var timer: NSTimer?
在你的@IBAction函数中:
if timer != nil {
timer?.invalidate()
timer = nil
} else {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
// Do everything you want with your timers
}