How to go back to previous view in Objective-C?

2019-04-24 08:58发布

I am a beginner in iOS programming and I want to implement the functionality of going back to home view.

I have use this code:

-(IBAction)onclickhome:(id)sender
{

    [self.navigationController popViewControllerAnimated:YES];
}

I have used navigationController in home button click event but it is not jump to home screen.

Do you have any suggestion and source code which applies to my code?

3条回答
Melony?
2楼-- · 2019-04-24 09:51

I'm not sure I understand your question.

What do you mean with

I have used navigationController in home button click event but it is not jump to home screen

?

If you want to pop to the root controller you can use popToRootViewControllerAnimated.

[self.navigationController popToRootViewControllerAnimated:YES];

From Apple doc of UINavigationController

popToRootViewControllerAnimated:

Pops all the view controllers on the stack except the root view controller and updates the display.
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated

If you have set up a UINavigationController and its root controller is called A, then if you navigate from A to B and then from B to C you have two possibilities to come back to a previous controller (you can have others but I list the main ones):

  • navigate back from C to B with popViewControllerAnimated
  • navigate back from C to A with popToRootViewControllerAnimated
查看更多
Ridiculous、
3楼-- · 2019-04-24 09:52

The best way to navigate back and forth views is by pushing and popping views from navigation view controller stack.

To go one view back, use below code. This will ensure that the smooth transition between views are retained.

UINavigationController *navigationController = self.navigationController;
[navigationController popViewControllerAnimated:YES];

To go two views back, do as below

UINavigationController *navigationController = self.navigationController;
[navigationController popViewControllerAnimated:NO];
[navigationController popViewControllerAnimated:YES];

If you aren't going back to your expected view, execute below code before popping any of the views...

UINavigationController *navigationController = self.navigationController;
NSLog(@"Views in hierarchy: %@", [navigationController viewControllers]);

You should see an array like the below one, which will help you in verifying the stack is maintained as expected.

Views in hierarchy: (
    "<Main_ViewController: 0x1769a3b0>",
    "<First_ViewController: 0x176a5610>",
    "<Second_ViewController: 0x176af180>"
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-24 09:54

I use

[self dismissViewControllerAnimated:YES completion:nil];

since others answers didn't worked in Xcode 8.0

查看更多
登录 后发表回答