Wednesday, 20 May 2015

swift navbar back button clicked event




http://stackoverflow.com/questions/8228411/detecting-when-the-back-button-is-pressed-on-a-navbar
http://stackoverflow.com/questions/27713747/execute-action-when-back-bar-button-of-uinavigationcontroller-is-pressed


1.
  override func viewWillDisappear(animated : Bool) {
    super.viewWillDisappear(animated)
    
    
    if(isMovingToParentViewController()){
      println("isMovingToParentViewController")  never get called
    }
    if(isMovingFromParentViewController()){
      println("isMovingFromParentViewController")    ---this is the key function
    }
    
    if (isBeingDismissed()) {
      println("isBeingDismissed")     this function never get called
    }
    
    if (isBeingPresented()) {
      println("isBeingPresented")  never get called
    }
    
  }
  
"isMovingFromParentViewController" is a very confusing function name.

It is a status flag, if you check it in viewWillAppear() function is already set.

So, it is a status flag to indicate it is a navigate page from navigated from root page。


2.

  override func willMoveToParentViewController(parent: UIViewController?) {
    super.willMoveToParentViewController(parent)
    
    println("This VC has has been pushed OR popped")
    
    if parent == nil {
      println("This happens ONLY when it's popped")
    }

  }

No matter this page will show or disappear, this function will get called.

But parent will equal to nil, if it is going to disappear and back to previous page.

This function page is more confusing that the function above.

But if you think about the previous page is the parent page that will be fine.



3.


  override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.setHidesBackButton(true, animated: false)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
  }
  
  // Then handle the button selection
  func goBack() {
    // Probably want to show an activity indicator
    
    self.navigationController?.popViewControllerAnimated(true)
    
    println("back")

  }

By this method, you created your own back button. so you may have risks of loosing style control and some build-in features such as showing previous page's title.





No comments:

Post a comment