仅当单击 UIButton 时才调用计时器函数

Call a timer function only when a UIButton is clicked

提问人:willd 提问时间:11/6/2023 最后编辑:General Grievancewilld 更新时间:11/14/2023 访问量:31

问:

我有一个函数,每次调用间隔时都想运行,但我只想在单击我的函数后执行。我的问题是,从我运行模拟器的那一刻起,该函数就会自行执行。为了防止这种情况发生,我尝试定义 a 并初始化为 因此,当单击 UIButton 时,它会将其设置为 true,然后检查初始布尔值更改是否会在控制台中打印“已选择”,但就像我说的,我甚至在单击按钮之前就看到它打印出来。UIButtonisPlayButtonClickedfalseplayAnimationwasPlayButtonClicked

 var setTimer: Timer!
 var isPlayButtonClicked: Bool = false

 @objc func playAnimation(_ sender: Any) {

         isPlayButtonClicked = true
        wasPlayButtonClicked()
    }

  func wasPlayButtonClicked() {
        if isPlayButtonClicked == true  {
            print("selected ")
        }
    }


    
    override func viewDidLoad() {
        super.viewDidLoad()

setTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(playAnimation(_:)), userInfo: nil, repeats: true)


}

如何让它等待我的点击事件执行?

Swift 计时器 UIKIT UIBuint

评论


答:

0赞 HangarRash 11/6/2023 #1

最简单的解决方法是更改计时器,使其调用选择器而不是选择器。wasPlayButtonClickedplayAnimation

更好的解决方法是触发函数中的计时器。在实际点击按钮之前,无需启动计时器。playAnimation

下面是对视图控制器的重新设计:

class SomeVC: UIViewController {
    var setTimer: Timer? // change to optional

    @objc func playAnimation(_ sender: Any) {
        setTimer?.invalidate() // Esnure there's only one timer even if the button is tapped multiple times
        // Change selector to wasPlayButtonClicked
        setTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(wasPlayButtonClicked), userInfo: nil, repeats: true)

        wasPlayButtonClicked()
    }

    @objc func wasPlayButtonClicked() {
        print("selected")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Don't setup the timer here
    }
}

请注意,您可能希望在关闭视图控制器时使计时器失效。

评论

0赞 willd 11/6/2023
我看到这要归功于@HangarRash