快速 for 循环睡眠 [英] swift for loop with sleep
问题描述
我有一个 Swift 4 ios 应用程序,它在按下按钮时显示随机消息和照片.这工作正常,但我想创建一个无限循环以在按下按钮时显示随机消息/照片.我尝试了几种方法来实现这一点,但都没有奏效.似乎标签和图像视图在主线程完成之前不会更新.以下是我目前尝试此方法的方法,它甚至不是无限循环,但仍然存在相同的问题.打印语句显示在调试窗口中,但标签和图像视图从未更新.
I have a Swift 4 ios app that displays a random message and photo when a button is pressed. This works fine but I want to create an endless loop to display the random message/photo when the button is pressed. I have tried several ways to accomplish this but none have worked. It seems the labels and imageviews will not update until the main thread has completed. Below is my current method of trying this, which is not even an endless loop but still have the same issue. The print statements show in the debug window but the label and imageview is never updated.
@IBAction func loveButtonPressed(_ sender: UIButton) {
nextNote()
}
func nextNote() {
for number in 1...1000 {
print("number is \(number)")
randomPhoto = Int(arc4random_uniform(18))
if randomPhoto == lastRandomPhoto {
randomPhoto = Int(arc4random_uniform(18))
}
photoDisplay.image = UIImage(named: photoArray[randomPhoto])
lastRandomPhoto = randomPhoto
randomNum = Int(arc4random_uniform(14))
if randomNum == lastRandomNum {
randomNum = Int(arc4random_uniform(14))
}
loveNote.text = msgArray[randomNum]
lastRandomNum = randomNum
print("end of loop before sleep")
sleep(6)
print("end of sleep")
}
}
推荐答案
您可以使用 Timer
代替...
You could use a Timer
instead...
var timer: Timer!
func nextNote() {
self.timer = Timer.scheduledTimer(timeInterval: 6.0, target: self, selector: #selector(self.setPhoto), userInfo: nil, repeats: true)
}
@objc func setPhoto() {
randomPhoto = Int(arc4random_uniform(18))
if randomPhoto == lastRandomPhoto {
randomPhoto = Int(arc4random_uniform(18))
}
photoDisplay.image = UIImage(named: photoArray[randomPhoto])
lastRandomPhoto = randomPhoto
randomNum = Int(arc4random_uniform(14))
if randomNum == lastRandomNum {
randomNum = Int(arc4random_uniform(14))
}
loveNote.text = msgArray[randomNum]
lastRandomNum = randomNum
}
func somethingToEndTheLoop() {
self.timer.invalidate()
}
这篇关于快速 for 循环睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!