2

I have a iOS View controller that can appear either from a SourceViewController, or as a result of clicking on " < Back " on Navigation Bar.

How do I find out if ViewController appeared as a result of user clicking/touching on " < Back " on Navigation bar.

user462455
  • 12,838
  • 18
  • 65
  • 96
  • Not getting your question properly! – Ketan Parmar Jul 29 '16 at 06:13
  • you should write a method on viewDidAppear to check if current UIVIewController is the last controller in the property viewControllers of navigationController – Mohsen Shakiba Jul 29 '16 at 07:14
  • @MohsenShakiba this is a good idea, but you still need to account for the initial showing of the view controller. – Losiowaty Jul 29 '16 at 08:32
  • @Losiowaty I thought he only wanted to know if the the controller is a result of back navigation, what do you mean by initial showing of ...? – Mohsen Shakiba Jul 29 '16 at 14:59
  • When this view controller will be first shown, it won't be from navigating back to it, as stated in the question (and as logic dictates). Therefore checking if it is the last view controller on the navigation stack will also be true, when it is first shown to the user. This may or may not be desired. – Losiowaty Jul 29 '16 at 15:16

1 Answers1

2

viewDidLoad will not be called when navigating back, so you can set some sort of flag there and reset it in appropriate place (maybe viewDidAppear?). As to if viewDidLoad will be called every time you open it from SourceViewController depends on your code - if you create a new instance every time, you should be fine.

As for an example :

class SampleViewController : UIViewController {
    var isOpenedFromBackNavigation = false

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if self.isOpenedFromBackNavigation {
            // code that should be run if we navigated back here
        }
        self.isOpenedFromBackNavigation = true
    }
}
Losiowaty
  • 7,911
  • 2
  • 32
  • 47
  • i think `viewDidAppear` will also called on the first load after `viewDidLoad` right? http://stackoverflow.com/questions/11254697/difference-between-viewdidload-and-viewdidappear – xmhafiz Jul 29 '16 at 08:20
  • Yes, that's why we use a flag to indicate if the view controller has already been shown. – Losiowaty Jul 29 '16 at 08:29