我是一枚剛學習iOS的菜鳥,項目中經常會涉及到UIViewController之間的跳轉,常用的就是PushViewController及PResentViewController,現在簡單介紹下他們之間的區別。
PushViewController是導航的方式跳轉,左右切換,與PopViewController對應,以棧的方式管理,可以把棧理解成一個瓶子,用戶能看到的就是瓶子最上面的東西。而PreSentViewController是模態的方式跳轉,上下切換,與dismissViewController對應。本質上是用一個模態ViewController遮住原來的ViewController,但是可以設置新模態窗口的尺寸,所以不一定會把舊的ViewController完全遮住(如果不設置,默認完全遮住)
假設有兩個頁面A、B,A為ViewController,B為SecondViewController,跳轉的幾種代碼如下:
從A->B
SecondViewController *secondViewController = [[SecondViewController alloc] init];[self.navigationController pushViewController:secondViewController animated:YES]; //[self.navigationController setNavigationBarHidden:YES animated:YES]; // 隱藏導航欄從B->A[self.navigationController popViewControllerAnimated:NO];這里有個坑,在使用PushViewController跳轉時發現沒起作用。不要著急,這是因為self.navigationController為nil,我們只要添加根視圖為NavigationController就行了。解決這個問題有兩個方法:1.storyboard的方式
在xcode->Editor->Embed In->Navigation Controller
2.代碼的方法,修改AppDelegate.m文件
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; ViewController *viewController = [[ViewController alloc] init]; UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController]; self.window.rootViewController = nav; [self.window makeKeyAndVisible]; return YES;}PreSentViewController方式
從A->BSecondViewController *secondViewController = [[SecondViewController alloc] init]; [self presentViewController:secondViewController animated:YES completion:^{ }];從B->A[self.navigationController dismissViewControllerAnimated:NO completion:^{ }];簡單的跳轉這樣已經可以實現了,但是我在網上看到另外一種跳轉方式,原因說是為了解決從A跳轉到B時導航欄消失的問題,但是我在項目中做懸浮框時也必須這樣寫,還不大理解,先貼出來SecondViewController *secondViewController = [[SecondViewController alloc] init]; UINavigationController *navigationcontoller = [[UINavigationController alloc]initWithRootViewController:secondViewController]; navigationcontoller.navigationBar.hidden = YES; [self presentViewController:navigationcontoller animated:YES completion:^{ }];
新聞熱點
疑難解答