您好我正在尝试使用我拥有的数组并更新标签,以便在一秒钟内显示数组中的每个元素。一个例子是我拥有数组[3,6,2]并且我的标签显示3然后等待一秒然后显示6然后等待一秒并显示2.我已经看到许多NSTimer示例使用更新函数执行此类操作但只有在数字上增加,从不尝试解析数组。有人可以帮忙吗?
我在UIButton中调用我的计时器并遇到了问题。计时器工作正常但我的计时器下的按钮功能中的代码在计时器和更新功能之前运行。我的代码生成一个随机的数字数组,然后应该显示它们一秒钟。这样做是正确的但我的计时器下的print语句在更新之前运行并在教科书中显示数字。我不知道为什么?计时器是否在不同的线程上运行?
func updateCountdown() {
if(numbersIndex <= numberLimit){
self.counter.text = String(numbers[numbersIndex])
}else if(numbersIndex == numberLimit+1){
self.counter.text = ""
}else{
timer!.invalidate()
timer=nil
}
numbersIndex+=1
}
@IBAction func startButton(_ sender: AnyObject){
startB.setTitle("", for: .normal)
var highestLength = 3
//for trialNumber in 0...11{
var numberSequence = Array(repeating:11, count: highestLength)
for count in 0...highestLength-1{
var randomNumber = Int(arc4random_uniform(10))
if(count>0){
while(numberSequence.contains(randomNumber) || randomNumber-1 == numberSequence[count-1]){
randomNumber = Int(arc4random_uniform(10))
}
}
numberSequence[count] = randomNumber
}
print(numberSequence)
self.numbers = numberSequence
self.numbersIndex = 0
self.numberLimit = numberSequence.count-1
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
print("this should be last")
//do other stuff too
//}
}
答案 0 :(得分:0)
var counter = 0
var list: [String] = ["Eggs", "Milk"]
override func viewDidLoad() {
super.viewDidLoad()
var timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}
func update() {
label.text = "\(list[counter])"
counter += 1
if (counter >= list.count) {
counter = 0
}
}
这是假设你的名字标签是标签