简体   繁体   中英

iOS Is my UIView visible on screen?

I have a custom UIView that with a timer displays the current time, which is set inside a UITableViewCell . Is there a way to detect that user is no longer viewing this custom UIView I have (say by navigating to a different tab)? I would like to stop this timer when my UIView is no longer visible on screen. I am using Swift.

I see there is a method I can override called didMoveToWindow , which seem to be triggered when I change tabs, but I'm not very experienced with iOS and what methods or properties to look for to tell if the view is actually visible to the user or not on screen.

I need some kind of method that are called, similar to viewDidAppear and viewDidDisappear for UIViewController .

Thanks in advance!

I found an answer to this that works for this purpose, simply override didMoveToWindow and check if self.window is nil or not:

override func didMoveToWindow() {
    if (self.window == nil) {
        timerStop()
    } else {
        timerStart()
    }
}

The best practice to handle action when the view is no longer displayed to the user is by overriding the viewWillAppear and viewDidDisappear functions.

To start your timer:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    timerStart()
}

Then to stop your timer:

override func viewDidDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    timerStop()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM