Search code examples
iosswiftuinavigationbaruinavigationitem

Hiding back button in viewDidLoad without animation


I'm using navigationItem.setHidesBackButton(true, animated:false) to hide back button in my iOS10 app in viewDidLoad. When I do this, on navigation bar, back button label is briefly shown (it is fading out) in presenting animation instead not showing it at all, after screen change, button is gone.

How I can prevent it from happening?


Solution

  • Suppose you are going from Controller A to Controller B. Currently you are applying self.navigationItem.hidesBackButton = true in the viewDidLoad of Controller B.

    Add this very same code when you are pushing from A to B in Controller A's viewWillDisappear OR prepareForSegue (if you are using segue)

    -(void)viewWillDisappear:(BOOL)animated{
         self.navigationItem.hidesBackButton = true;
    }
    

    A safer option is in prepareForSegue as viewWillDisappear will get called whenever this Controller A is going OFF-SCREEN. But in prepareForSegue, you can check that the following code will work only when its going from Controller A to Controller B, by the following

    Suppose the segue connecting from Controller A to Controller B is named "SEGUE_NAME"

     -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
        if([[segue identifier]isEqualToString:@"SEGUE_NAME"]){
           /*
            this means it is going from Controller A to Controller B
            via segue "SEGUE_NAME"
          */
          self.navigationItem.hidesBackButton = YES;
         }
      }
    

    I think this would be the swift version : Forgive me if the syntax isn't appropriate

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "SEGUE_NAME"){
            self.navigationItem.hidesBackButton = true;
        }
     }