swift for while with sleep

时间:2018-03-28 03:36:22

标签: ios swift4

我有一个Swift 4 ios应用程序,当按下按钮时会显示随机消息和照片。这很好但我想创建一个无限循环来按下按钮时显示随机消息/照片。我已经尝试了几种方法来实现这一点但没有一种方法可行。在主线程完成之前,标签和图像视图似乎不会更新。下面是我目前的尝试方法,这甚至不是无限循环但仍然有相同的问题。打印语句显示在调试窗口中,但标签和imageview永远不会更新。

@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")
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用Timer代替......

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()
}

答案 1 :(得分:0)

我建议使用DispatchQueue。使用它你不需要创建一个繁重的计时器对象,你也可以确保你的代码在没有其他任务的情况下在主线程上运行。

@IBAction func loveButtonPressed(_ sender: UIButton) {
    nextNote()
}   

func nextNote() {
    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

    let deadlineTime = DispatchTime.now() + .seconds(6)
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
        nextNote()
    }
}