iOS實戰演練之對於present出來的UINavigationController返回的問題
阿新 • • 發佈:2019-01-09
如題,現在我們控制頁面present到一個UINavigationController頁面去
SCMyCardDesignCollectionViewController *vc = [[SCMyCardDesignCollectionViewController alloc]initWithCollectionViewLayout:layout];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
[self presentViewController:nav animated:YES completion:nil];
SCMyCardDesignCollectionViewController.m
中
注意“返回”一定要寫在返回按鈕所在的ViewController頁面中
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector (backMain:)];
}
這時候backMain:
方法有兩種:
1、present到新頁面(也可以是首頁)
-(void)backMain:(id)sender{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
SCTabBarController *vc = [storyboard instantiateInitialViewController];
[self presentViewController:vc animated:YES completion:nil];
[self.navigationController popViewControllerAnimated:YES];
}
2、直接dismiss掉這個ViewController
-(void)backMain:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
從效果來說我更推薦第二種,第一種出現的效果是從下往上present出一個頁面,第二個效果上更符合返回的要求。
對與正常的UINavigationController返回總結:
1、彈出當前檢視控制器(彈出並向左顯示前一個檢視)
[self.navigationController popViewControllerAnimated:YES];
2、彈出到指定檢視控制器(回到指定檢視控制器,也就是不只彈出一個)
[self.navigationController popToViewController:viewController animated:YES];
3、彈出到根檢視控制器(比如說你有一個“Home”鍵,也許就會實施這個方法了)
[self.navigationController popToRootViewControllerAnimated:YES];
具體應用如下:
假設我的一個navigationController裡共有4個viewcontroller,要是在每層ViewController返回上一層ViewController,有一個很簡單方法:
[self.navigationController popViewControllerAnimated:YES];
當然,要想直接返回到根viewcontroller也有現成的方法:
[self.navigationController popToRootViewControllerAnimated:YES];
不過想要從第5層直接返回到第2層或第3層,則沒有現成的方法可以呼叫了。
但這時若能夠知道pop回去的ViewController的指標,也就好辦了。
具體寫法如下:
[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -2)] animated:YES];
在使用時,根據自己返回層的需要,只要改變一下“-2”這個數字就可以達到目的了。