iosswiftviewwillappear

viewWillAppear not called when going back on a UINavigationController


I have some code I call that changes the language in the viewWillAppear section of a viewcontroller inside a navigation controller. enter image description here

When I hit the back button the language change doesn't take place even though I have code for it to in the viewWillAppear. The only time it switches is when I hit back all the way to the original screen and then start moving forward it changes. Is there any way to have the function in the viewWillAppear work?

Here is my code, I'm using a language changing pod:

  //MARK: Language change

  //used to change language text for imediate screens
  func setText(){
    locationsLabel.text = "Locations".localized()
    languageLabel.text = "Languages".localized()
    termsOfUseLabel.text = "Terms of Use".localized()
    privacyPolicyLabel.text = "Privacy Policy".localized()
    pushNotificationsLabel.text = "Push Notifications".localized()
    contactUsLabel.text = "Contact Us".localized()
  }


  // Changes text to current language
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "setText", name: LCLLanguageChangeNotification, object: nil)
  }

  // Remove the LCLLanguageChangeNotification on viewWillDisappear
  override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self)
  }

Solution

  • The viewWillAppear method is only adding a notification observer. The observer is removed in viewWillDisappear. This means that setText will only be called if the LCLLanguageChangeNotification notification is sent while the view is visible.

    The update stops as soon as the view goes off-screen due to the navigation behaviour.

    To ensure that the text is updated, you also need to call setText inside viewWillAppear:

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        setText()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "setText", name: LCLLanguageChangeNotification, object: nil)
    }