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

如何在UIViewController首次呈现时,点击UIButton仅调用一次savedFunc?

实现点击按钮时仅首次调用savedFunc的方案

完全可以实现,核心是通过标记变量记录savedFunc是否已经执行过,以下是两种适配不同场景的方案:

方案一:仅当前APP会话生效(重启APP后重置状态)

在你的ViewController类中添加一个私有布尔属性,用来标记函数是否已执行:

private var hasCalledSavedFunc = false

修改点击事件方法,仅当标记为false时执行savedFunc,执行后将标记设为true:

@objc func returnToView(_ sender: UIButton) {
    let vsdd = SavedCanvasViewController()

    if !hasCalledSavedFunc {
        savedFunc()
        hasCalledSavedFunc = true
    }
 
    vsdd.modalPresentationStyle = .fullScreen
    vsdd.modalTransitionStyle = .coverVertical
    present(vsdd, animated: true)
}

方案二:持久化生效(APP重启后保持状态)

如果需要标记在用户退出APP再打开后依然有效,可使用UserDefaults存储状态:

先将标记属性改为从UserDefaults读写:

private var hasCalledSavedFunc: Bool {
    get { UserDefaults.standard.bool(forKey: "HasCalledSavedFunc") }
    set { UserDefaults.standard.set(newValue, forKey: "HasCalledSavedFunc") }
}

点击事件的逻辑和方案一完全一致,无需额外修改。这样即使APP重启,只要之前执行过一次savedFunc,再次点击按钮就不会重复调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 12:43:19