模态视图由模态视图控制器控制,模态视图控制器对应的页面对应着一个类,这个类事主视图控制器类的子类,需要我们去建的。主视图控制器(UIViewController)有两个方法:
1.开模态视图控制器法:presentViewController:animated:completion
2.关模态视图控制器法:dismissViewControllerAnimated:completion
正是因为UIViewController拥有这两种方法,就赋予了其子类(模态视图控制器类)都拥有这样的方法,在其中都可以进行开关模态视图控制器的操作。
开模态视图控制器有两种方法:
1.拖拽按钮(如:注册)致模态视图控制器对应的导航控制器,选Present Modally;
2.在模态视图控制器(代码)文章中讲述;
用IB实现模态视图控制器方法如下:
1.设置RegisterViewController类
#import "RegisterViewController.h"
@interface RegisterViewController ()
@property (weak, nonatomic) IBOutlet UITextField *txtUsername;
- (IBAction)cancel:(id)sender;
- (IBAction)save:(id)sender;
@end
@implementation RegisterViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:TRUE completion:^{
NSLog(@"点击Cancel按钮,关闭模态视图");
}];
}
- (IBAction)save:(id)sender {
[self dismissViewControllerAnimated:TRUE completion:^{
NSDictionary *dataDict = @{@"username":self.txtUsername.text};
[[NSNotificationCenter defaultCenter]postNotificationName:@"RegisterCompletionNotification" object:nil userInfo:dataDict];
}];
}
@end
2.设置主视图控制器类
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *LogIn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//回调通知中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerCompletion:) name:@"RegisterCompletionNotification" object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
//关闭通知中心
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//通过回调通知中心拿到的数据,做些操作
-(void)registerCompletion:(NSNotification*)notification{
NSDictionary *theData = [notification userInfo];//注册类中的userInfo
NSString *username = theData[@"username"];
_LogIn.text = username;//把值赋值给登陆框
}
@end