IOS Is my UIView visible on screen?

I have a custom UIView

one that with a timer displays the current time, which is set internally UITableViewCell

. Is there a way to detect that the user no longer views this user UIView

that I have (say by going to a different tab)? I would like to stop this timer when mine is UIView

no longer displayed on the screen. I am using Swift.

I see that there is a method that I can override, called didMoveToWindow

, that seems to fire when the tabs change, but I am not very good at iOS and what methods or properties are looking for to determine whether the user is actually visible on the screen or not.

I need some kind of method that gets called similar to viewDidAppear

and viewDidDisappear

for UIViewController

.

Thanks in advance!

+3


source to share


2 answers


I found an answer to this question that works for this purpose, it just overrides didMoveToWindow

and checks if it is self.window

null or not:



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

      

+7


source


The best practice for handling actions when the view is no longer displayed to the user is to override the viewWillAppear and viewDidDisappear functions.

To start a timer:

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

    timerStart()
}

      



Then, to stop your timer:

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

    timerStop()
}

      

0


source







All Articles