简体   繁体   English

仅当特定ViewController处于前台时,iOS Swift调用函数

[英]iOS Swift Call Function Only When Particular ViewController Is In Foreground

In my app I am having two view controller viewcontroller1 and viewcontroller2 . 在我的应用程序中,我有两个视图控制器viewcontroller1viewcontroller2 In view controller1 I am having one function called UpdateView() I need to call this function for every 60 seconds and I did it using DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 60) . view controller1 1中,我有一个名为UpdateView()函数,我需要每60 seconds调用一次此函数,并使用DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 60)做到了。 My problem is I want to run this function only when viewcontroller1 is in foreground, when user moved to viewcontroller2 I don't want to run this function any more. 我的问题是我只想在viewcontroller1处于前台时运行此功能,而当用户移至viewcontroller2我不再希望运行此功能。 How to solve this? 如何解决呢?

您应该在viewDidDisappear中停止计时器,并在ViewController1中的viewDidAppear中启动计时器逻辑。

You can do this easily with a Timer . 您可以使用Timer轻松完成此操作。 Inside viewWillAppear method start the timer and inside the viewWillDisappear stop or pause the timer. viewWillAppear方法内部启动计时器,在viewWillDisappear内部停止或暂停计时器。

var myTimer:Timer!
var myTimeInterval:TimeInterval = 60

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        myTimer = Timer.init(fire: Date(), interval: myTimeInterval, repeats: true, block: { (aTimer) in
            //call the functio you want
            UpdateView()
        })
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        myTimer.invalidate()
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当 ViewController 可见时 Swift 调用 Function - Swift call Function when ViewController is visible 如何仅在需要时添加ViewController滚动? iOS /迅捷 - how to add viewcontroller scroll only when it is needed? IOS/swift Swift:在另一个ViewController中调用一个函数 - Swift: Call a function in another ViewController 当应用程序在 swift 3 中处于前台时隐藏特定视图控制器的远程通知 - Hide remote notification at specific viewcontroller when app is in foreground in swift 3 当应用程序在 SWIFT 中进入前台时如何呈现 Lock_ViewController? - How to present Lock_ViewController when app is entering foreground in SWIFT? 使用 Swift IOS 的不同 ViewController 中的相同功能 - Same Function in different ViewController using Swift IOS 来自父 ViewController 的 swift 3 调用函数 - swift 3 call function from parent ViewController 从 ViewController Swift 中的 UITableViewCell 调用 function - Call function from UITableViewCell from in ViewController Swift Swift,如何在其他viewcontroller中调用函数? - Swift, how to call a function in other viewcontroller? Swift:从其他Viewcontroller调用PageViewController中的函数 - Swift: Call Function in PageViewController from other Viewcontroller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM