Swift N定时器时间间隔未正确触发
我有一个调用函数的NSTimer。该功能每次调用时都会闪烁不同的按钮。我将时间间隔设置为1秒,repeats为true,当变量pcChoice==10时,它停止重复,但由于某种原因,当我运行程序时,它会延迟1秒,然后依次调用函数多次。对用户来说,它看起来就像一秒钟过去了,然后一次闪动了许多按钮。我需要的是每个按钮一个接一个地闪烁,每次闪烁之间间隔一秒钟Swift N定时器时间间隔未正确触发,swift,uibutton,nstimer,Swift,Uibutton,Nstimer,我有一个调用函数的NSTimer。该功能每次调用时都会闪烁不同的按钮。我将时间间隔设置为1秒,repeats为true,当变量pcChoice==10时,它停止重复,但由于某种原因,当我运行程序时,它会延迟1秒,然后依次调用函数多次。对用户来说,它看起来就像一秒钟过去了,然后一次闪动了许多按钮。我需要的是每个按钮一个接一个地闪烁,每次闪烁之间间隔一秒钟 override func viewDidLoad() { var lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o
override func viewDidLoad() {
var lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
var litIndex = 0
super.viewDidLoad()
for i in 1...10{
print(randomIndex)
print(computerChoices)
var buttonChoice = lit[randomIndex]
randomIndex = Int(arc4random_uniform(UInt32(lit.count)))
computerChoices[i] = randomIndex
print("yoyoyo")
self.view.setNeedsDisplay()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("flashingButtons"), userInfo: nil, repeats: true)
}
}
func flashingButtons(){
var lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
one = computerChoices[pcChoice]
lit[one].setImage(UIImage(named: "redb.png"), forState: UIControlState.Normal)
pcChoice += 1
if pcChoice == 10{
timer.invalidate()
}
}
这条线
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("flashingButtons"), userInfo: nil, repeats: true)
由于您的for
循环,执行了10次。这将为您提供10个不同的计时器,每个计时器将在大约1秒后调用flashingButtons
。将该呼叫移出循环。您也不需要在viewDidLoad
中调用10次setNeedsDisplay
由于不修改lit
,因此将其设置为let
,而不是var
。我还注意到,lit
中有9个元素,但循环了10次。从不使用viewDidLoad
中的lit
数组,它与flashingButtons
中的数组不同
每次触发时,您都可以调用arc4random_uniform
内部flashingbutton
。或者,如果您想让灯光真正混洗,每个灯光都被击中一次,请使用GameplayKit尝试以下操作:
let lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
let shuffledLit : [<lightobjects>] // whatever type of b0o, etc is
override func viewDidLoad() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("flashingButtons"), userInfo: nil, repeats: true)
shuffledLit = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(lit)
super.viewDidLoad()
self.view.setNeedsDisplay()
}
let lit=[b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
让shuffledLit:[]//不管b0o的类型是什么,等等
重写func viewDidLoad(){
timer=NSTimer.scheduledTimerWithTimeInterval(1,目标:self,选择器:选择器(“flashingButtons”),userInfo:nil,repeats:true)
shuffledLit=gkramonSource.SharedAndom().arrayByShufflingObjectsInArray(lit)
super.viewDidLoad()
self.view.setNeedsDisplay()
}
为什么要在viewDidLoad中创建10倍的计时器?self.view.setNeedsDisplay()10x在该方法中不需要多次触发,这就是为什么我在for i循环中只触发一次,并控制它在选择器方法中执行多少次是什么意思将随机数调用放在flashingButtons中而不是在viewDidLoad中?对不起,我是新来的斯威夫特。