這是一篇邊學邊記的筆記。筆者原本寫 Android,剛轉到 iOS 時,最想先搞懂的莫過於「頁面到底怎麼跳」。翻了不少資料,乾脆把常見做法整理下來,方便日後回頭查閱。
整體來說,跳轉主要有兩條路:一是借助 UINavigationController 的導航堆疊,二是直接以模態方式彈出。下面分別說明。
先在 AppDelegate 裡建立一個根控制器 RootViewController,並把它包進導航控制器。
delegate.h 中宣告屬性:
@property (strong, nonatomic) UIViewController *viewController; @property (strong, nonatomic) UINavigationController *navController;
接著在 delegate.m 的 didFinishLaunchingWithOptions 方法裡撰寫初始化程式碼:
RootViewController *rootView = [[RootViewController alloc] init]; rootView.title = @"Root View"; self.navController = [[UINavigationController alloc] init]; [self.navController pushViewController:rootView animated:YES]; [self.window addSubview:self.navController.view];
這段程式碼會載入第一個頁面 RootViewController。若要跳到其他頁面(例如 SubViewController),只需:
SubViewController *subView = [[SubViewController alloc] init]; [self.navigationController pushViewController:subView animated:YES]; subView.title = @"Sub";
這種做法的好處是系統會自動生成返回按鈕,導航體驗也更貼近原生。
如果不需要導航列,也可以乾脆新建一個 view 對象直接彈出:
SubViewController *subView = [[SubViewController alloc] initWithNibName:@"SubViewController" bundle:[NSBundle mainBundle]]; [self presentModalViewController:subView animated:YES];
需要留意的是,presentModalViewController: 在 iOS 6.0 之後已被捨棄,建議改用:
[self presentViewController:subView animated:YES completion:nil];
實務上常見的需求是:view1 跳到 view2 時,順便把 view1 的數據一起帶過去。思路其實很簡單:
1. 自定義一個 User 類,在 view2 中把它作為成員變量。
2. view1 跳轉前把數據封裝成 User 對象,賦值給 view2 的 user 屬性。
具體程式碼如下。先在 view2 的 .h 中聲明成員變量:
@property (strong, nonatomic) User *user;
再在 view1 中封裝數據並完成跳轉:
View2 *view2 = [[View2 alloc] init]; User *user = [[User alloc] init]; user.name = @"kevin"; view2.user = user; [self.navigationController pushViewController:view2 animated:YES];
最後在 view2 中取值即可:
self.user.name
以上就是 iOS 頁面跳轉與數據傳遞的基礎用法,寫下來當作自己複習的小抄。