You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Timer函数仅在点击UIButton后才执行?

解决方案

问题根源

你当前代码在viewDidLoad里直接调用了Timer.scheduledTimer,视图加载完成后会立刻启动定时器,自动触发playAnimation方法,所以没点按钮就出现了打印内容。

修正代码

var setTimer: Timer? // 用可选类型,初始为nil,便于判断定时器状态
var isPlayButtonClicked: Bool = false

// 按钮点击事件:仅负责启动定时任务
@objc func playAnimation(_ sender: Any) {
    // 避免重复点击创建多个定时器
    guard setTimer == nil else { return }
    
    isPlayButtonClicked = true
    // 创建并启动定时器,指定定时执行的任务函数
    setTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(repeatedTask), userInfo: nil, repeats: true)
}

// 定时器重复执行的任务逻辑
@objc func repeatedTask() {
    if isPlayButtonClicked {
        print("selected")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    // 此处不再初始化定时器,仅做基础视图配置
}

可选优化(停止定时器)

如果需要停止定时任务,可以添加如下逻辑:

@objc func stopAnimation(_ sender: Any) {
    setTimer?.invalidate()
    setTimer = nil // 置为nil,允许后续重新启动定时器
    isPlayButtonClicked = false
}

修改后只有点击playAnimation按钮才会启动定时任务,每隔2秒执行一次打印操作,彻底解决未点击就自动执行的问题。

内容的提问来源于stack exchange,提问作者willd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:14:54