除了 push 之外,Modal 是另一種常見的控制器切換方式。任何控制器都能透過 Modal 形式呈現出來,預設效果是新控制器從螢幕最底部往上鑽出,直到完全蓋住前一層控制器為止。
在 App 代理中建立 window 與初始控制器。
YYAppDelegate.m:
#import "YYAppDelegate.h"
#import "YYViewController.h"
@implementation YYAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 1. 建立 window 並設定 frame
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// 2. 設定背景色為黑色
self.window.backgroundColor = [UIColor blackColor];
// 建立一個控制器作為根控制器
YYViewController *one = [[YYViewController alloc] init];
self.window.rootViewController = one;
// 3. 設為主視窗並顯示
[self.window makeKeyAndVisible];
return YES;
}
@end
YYViewController.m:
#import "YYViewController.h"
#import "YYtwoViewController.h"
@interface YYViewController ()
// 點擊時跳轉到第二個界面
- (IBAction)jump2two:(UIButton *)sender;
@end
@implementation YYViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)jump2two:(UIButton *)sender {
// 建立新的 modal
YYtwoViewController *two = [[YYtwoViewController alloc] init];
// 用導航控制器包裝,讓彈出的模態窗口有導航欄可放返回按鈕
UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:two];
[self presentViewController:nvc animated:YES completion:^{
NSLog(@"彈出一個模態窗口");
}];
}
@end
YYtwoViewController.m:
#import "YYtwoViewController.h"
@implementation YYtwoViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 給導覽條加上返回按鈕
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回"
style:UIBarButtonItemStylePlain
target:self
action:@selector(change)];
}
-(void)change {
// 點擊返回按鈕,移除當前模態窗口
// 寫法一:透過 navigationController 關閉
// [self.navigationController dismissViewControllerAnimated:YES completion:^{
// NSLog(@"移除模態窗口");
// }];
// 寫法二:若控制器是以模態形式呈現,可直接呼叫自身或子控制器的 dismiss
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@"移除");
}];
}
@end
一、Modal 彈出時,後方的視圖無法被點擊,這是模態的本質——它代表一段必須先完成的中斷流程。
二、一次只能彈出一個 Modal。若試圖再彈一個,系統會拋出 Attempt to present ... while a presentation is in progress 的警告。
三、關閉時,presentViewController 與 dismissViewControllerAnimated 兩種呼叫方式都可以,重點是誰呈現、就由誰關閉,否則容易出現畫面卡住的情形。
四、實務判斷:控制器之間關係緊密、有明確的層級流轉時用導航控制器;關係鬆散、屬於輔助性任務(例如相簿挑選、分享、登入)時用 Modal。