How to get the previous viewcontroller that pushed

2019-02-02 21:04发布

The home page of my app has UIButtons, btnIncome and btnExpense. Pressing on this buttons pushes IncomeVC and ExpenseVC respectevely,which are two UIViewControllers with UITabBar added via xib. The tabBar have 4 items. Selecting on each tab item adds same four view controllers(which contains UITableViews) as the subview of IncomeVC and ExpenseVC,like for eg, DailyVC,WeeklyVC,MonthlyVC,YearlyVC.(ie,for Income ,there is daily,weekly etc and same for Expense) (I have done like that because the IncomeVC and ExpenseVC have a UIButton and a UIView which is common for all tabs).

So the problem is that, if click the btnIncome I have to populate those tableviews with the arrays related to Income and vice versa for Expense. How can I find from which viewController I selected the different tabs(I need to get it from the 4 Views I added as the subview of IncomeVC and ExpenseVC). Do I have to make 8 different views 4 each for Income and expense ? Thanx.

10条回答
再贱就再见
2楼-- · 2019-02-02 21:19

In Swift:

let n: Int! = self.navigationController?.viewControllers?.count
let myUIViewController = self.navigationController?.viewControllers[n-2] as! UIViewController
查看更多
萌系小妹纸
3楼-- · 2019-02-02 21:25

Swift

extension UINavigationController {
    func getPreviousViewController() -> UIViewController? {
        let count = viewControllers.count
        guard count > 1 else { return nil }
        return viewControllers[count - 2]
    }
}
查看更多
倾城 Initia
4楼-- · 2019-02-02 21:27

Swift 4.1, 4.2

let allPreviousViewC = currentViewController.navigationController?.viewControllers // will give array of all pushed VC
for viewC in allPreviousViewC! {
       print("ViewC is \(viewC)")
  }
查看更多
▲ chillily
5楼-- · 2019-02-02 21:30
UIViewController *previousViewController = [[[self navigationController]viewControllers] objectAtIndex:([viewControllers indexOfObject:self]-1)];

Where self will be current view controller.

查看更多
登录 后发表回答