gpt4 book ai didi

swift - 如何停止循环 swift 3

转载 作者:行者123 更新时间:2023-11-28 06:19:51 25 4
gpt4 key购买 nike

我正在尝试制造一种滴答声,这种声音一直持续到您按下减号按钮为止。我遇到的唯一问题是我无法单击减号按钮,因为加号按钮一直处于按下状态。它可能一直处于按下状态,因为它无法退出循环。已经感谢您的回答!

import UIKit
import AVFoundation
import AudioToolbox
import Foundation

class ViewController: UIViewController {
@IBOutlet weak var telLabel: UILabel!

var number = 0
var timeline = "no"

@IBAction func plus(_ sender: Any) {
number += 1
telLabel.text = "\(number)"
timeline = "yes"
tijdlijn()
}

func tijdlijn(){
while timeline == "yes"{
AudioServicesPlaySystemSound(SystemSoundID(1103))
sleep(2)
}
}

/* if timeline = "yes"{
repeat{
AudioServicesPlaySystemSound(SystemSoundID(1103))
sleep(3)
} while timeline == "yes"
*/

//4095
@IBAction func min(_ sender: Any) {
number -= 1
telLabel.text = "\(number)"
timeline = "no"
}
}

最佳答案

我建议你使用 Timer 来完成这样的任务。尝试使用这个:

@IBOutlet weak var telLabel: UILabel!

var number = 0

var timeline = false

var timer: Timer!

@IBAction func plus(_ sender: Any) {

timeline = !timeline

if timeline {
number += 1
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.tijdlijn), userInfo: nil, repeats: true)

} else {
number -= 1

timer.invalidate()
}

telLabel.text = "\(number)"
}

func tijdlijn(){
AudioServicesPlaySystemSound(SystemSoundID(1103))
}

并且只使用一个 Action touchupinside - func plus。删除减号 touchupinside 操作。

关于swift - 如何停止循环 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com