5

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 viewDidAppearand viewDidDisappearfor UIViewController.

Thanks in advance!

Bjarte
  • 2,167
  • 5
  • 27
  • 37
  • possible duplicate of [How to tell if UIViewController's view is visible](http://stackoverflow.com/questions/2777438/how-to-tell-if-uiviewcontrollers-view-is-visible) – Daniel Oct 08 '14 at 11:31
  • I disagree, I have update the text to clarify. I need a way to get notified when it is in view and when it goes way. If I need a timer or something to do that, then the whole point of stoping the timer when I go out of view is gone. – Bjarte Oct 08 '14 at 11:36

2 Answers2

13

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()
    }
}
Bjarte
  • 2,167
  • 5
  • 27
  • 37
0

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()
}
Nubji
  • 9
  • 3
  • 1
    `viewWillAppear` and `viewDidDisappear`comes from `UIViewController` so I can't use these unless I have a `UIViewController` that I create these events and that totally goes against the purpose I'm after. I have a viewcontroller -> tableview -> tableviewcell -> mylabelclass, so I need something that is standalone in my labelclass and not tightly coupled. – Bjarte Oct 09 '14 at 06:32
  • Ok, sorry my bad. Then the two methods you are looking for are `awakeFromNib` (to start your timer) and `deinit` (to stop it). Try this and let me know if this solves your problem. – Nubji Oct 10 '14 at 07:36