默认情况下,模态视图是从屏幕下方滑出来的。当完成的时候需要关闭这个模态视图,如果不关闭,就不能做别的事情,这就是“模态”的含义,它具有必须处理的意思。
主要由以下几个方法控制:
/*
The next two methods are replacements for presentModalViewController:animated and
dismissModalViewControllerAnimated: The completion handler, if provided, will be invoked after the presented
controllers viewDidAppear: callback is invoked.
*/
// 呈现模态视图
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion ;
// The completion handler, if provided, will be invoked after the dismissed controller's viewDidDisappear: callback is invoked.
//关闭模态视图
- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion ;
它还有一个控制模态视图呈现方式的参数: modalTransitionStyle,是个枚举类型:
typedef NS_ENUM(NSInteger, UIModalTransitionStyle) {
UIModalTransitionStyleCoverVertical = 0,
UIModalTransitionStyleFlipHorizontal,
UIModalTransitionStyleCrossDissolve,
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
UIModalTransitionStylePartialCurl,
#endif
};
2. 在默认创建的storyboard文件中,拖一个新的UIViewController,并将它的custom class 指定为先前创建的StartGameViewController ,并将它的 storyboard ID 命名。如图:
3. 模态视图呈现:
- (IBAction)startGameBtnClick:(UIButton *)sender
{
NSBundle *bundle = [NSBundle mainBundle];
// 获得项目中默认创建的 storyboard 文件,它的名字即该文件名,不包括后缀
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:bundle];
// 必须通过storyboard来找到那个类,不能通过 alloc-》init 的方法来获得。
StartGameViewController *gameVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"StartGamePage"];
//设置模态视图呈现样式
gameVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:gameVC animated:YES completion:^{
// 模态视图呈现后
NSLog(@"开始游戏");
}];
}
4. 关闭模态视图:
[self dismissViewControllerAnimated:YES completion:^{
// 关闭模态视图完成
}];
5. 模态视图参数回传:方法有很多种,以下是通过广播机制类实现参数传递。
(1)在默认创建的那个VC中的 viewDidLoad 方法中添加一个广播观察者:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSendParams:) name:@"CompletionNotification" object:nil];
}
- (void)getSendParams:(NSNotification *)notification
{
NSDictionary *theData = [notification userInfo];
// 获取回传参数
NSString *userName = [theData objectForKey:@"username"];
}
(2)在另一个需要发回参数的VC类中的 关闭模态视图的回调block中添加发送广播代码:
[self dismissViewControllerAnimated:YES completion:^{
// 关闭模态视图完成
NSDictionary *data = [NSDictionary dictionaryWithObject:@"Aboo" forKey:@"username"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"CompletionNotification" object:nil userInfo:data];
}];