How to get the previous viewcontroller that pushed my current view

后端 未结 10 381
礼貌的吻别
礼貌的吻别 2020-12-28 14:08

The home page of my app has UIButtons, btnIncome and btnExpense. Pressing on this buttons pushes IncomeVC and Expen

相关标签:
10条回答
  • 2020-12-28 14:24

    You can get the previous viewController like following code,

    NSLog(@"%@",[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2]);
    

    This will displays the previous viewController name...

    0 讨论(0)
  • 2020-12-28 14:28

    You can certainly reuse the view controllers. I would suggest instead of pushing UIViewController (which contains UITabBar added from IB) when the button is pressed, you can push UITabBarController which contains 4 View Controllers (daily, weekly, monthly, and yearly).

    You UITabBarController could have an enum property (Income and Expense) and this can be assigned when you push this UITabBarController based on the button pressed. From there, you can assign another enum property (Income and Expense) to the 4 UIViewControllers to show the correct type of data in each view controller.

    0 讨论(0)
  • 2020-12-28 14:29

    If the reason for needing access to the previous view controller is to know what data to get, I would suggest that you instead give the new view controller the data before you push it on the stack. Or at least enough data so that the view controller know how to get the right data, e.g. a enum or constant or something.

    This could be done with a custom initializer, or a property. Take a look at this blog post for an example: "Passing Data Between View Controllers"

    If you are using a storyboard, you can use prepareForSegue:sender to pass the right data. A good tutorial on that can be found here: Beginning Storyboards in iOS 5 Part 2

    0 讨论(0)
  • 2020-12-28 14:30

    Swift 5.1

    0 讨论(0)
  • 2020-12-28 14:31

    Check out this post: How to identify previous view controller in navigation stack Tony is right, you can get the previous VC from the viewControllers array but at index n-2.

    0 讨论(0)
  • 2020-12-28 14:33
    UIViewController *previousViewController = [[[self navigationController]viewControllers] objectAtIndex:([viewControllers indexOfObject:self]-1)];
    

    Where self will be current view controller.

    0 讨论(0)
提交回复
热议问题