简体   繁体   中英

Change View Controller with another view Controller swift

Suppose I have view controllers named A, B, C, D. I am using push to go from A -> B -> C. Now I want to go to D from C and when I press back button from D, it should go to A. How Can I do that? Any suggestions?

if you want to pop to root (A), for example D --> A (directly)

 self.navigationController?.popToRootViewControllerAnimated(true)

If you want to go back to the previous view controller , for ex : D -- > C or c--> B or B to A

 self.navigationController?.popViewControllerAnimated(true)

You need to modify your back button with a custom one, and add an action which will pop you to the rootViewController inside that UINavigationController you are currently. ( popToRootViewController means removing all other controllers from the navigation stack and go the first one)

On your last viewController put these lines:

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Go to root" style:UIBarButtonItemStylePlain target:self action:@selector(popToRootNavigationViewController:)];
}

- (void)popToRootNavigationViewController:(UIBarButtonItem *)button {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

Swift

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Go to root", style: UIBarButtonItemStyle.Plain, target: self, action: "popToRootNavigationViewController:")
}

func popToRootNavigationViewController(sender: UIBarButtonItem) {
    self.navigationController?.popToRootViewControllerAnimated(true)
}

Using a UINavigationController you can call popToRootViewControllerAnimated(_:) , it will take you back to the first controller of your pile.

So use a NavController, set A as root, and in D, popToRootViewControllerAnimated(true)

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationController_Class/#//apple_ref/occ/instm/UINavigationController/popToRootViewControllerAnimated :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM