模态框视图
1、利用xib自定义一个新的ViewController ModalPageController;
2、在原有的视图控制器中触发跳转,代码如下:
ModalPageController *modelPageController = [[ModalPageController alloc]initWithNibName:@"ModalPageController" bundle:nil]; modelPageController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentViewController:modelPageController animated:YES completion:^{ NSLog(@"modelPageController"); }];
3、在ModalPageController中返回,代码如下:
[self dismissViewControllerAnimated:YES completion:^{ NSLog(@"Close"); }];
4、两个 ViewController之间的数据交换:
4.1 利用 NSNotificationCenter
1)在原有的ViewController总定义并设置回调,代码如下:
//viewDidLoad里 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doComplete:) name:@"testComplete" object:nil]; //定义回调函数 -(void)doComplete:(NSNotification*)notification{ NSDictionary *data = [notification userInfo]; if(nil != data){ NSString *input = [data objectForKey:@"InputText"]; NSLog(@"%@", input); } }
2)在ModalPageController的返回中,实现通知:
[self dismissViewControllerAnimated:YES completion:^{ NSLog(@"Close"); NSString *input = self.inputText.text; NSDictionary *dic = [NSDictionary dictionaryWithObject:input forKey:@"InputText"]; [[NSNotificationCenter defaultCenter]postNotificationName:@"testComplete" object:nil userInfo:dic]; }];
4.2 利用协议
1)定义一个protocal
#import <Foundation/Foundation.h> @protocol doBack <NSObject> -(void)getInputText:(NSString *)input; @end
2)定义原ViewController遵循并实现该协议,如下:
#import <UIKit/UIKit.h> #import "doBack.h" @interface ViewController : UIViewController<doBack> @end -(void)getInputText:(NSString *)input{ NSLog(@"%@", input); }
3)、在ModelPageController中定义代理,并在跳转前将该代理指向原ViewController
//ModalPageController.h中 @property(nonatomic,assign) NSObject<doBack> *delegate; // ModalPageController *modelPageController = [[ModalPageController alloc]initWithNibName:@"ModalPageController" bundle:nil]; modelPageController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; modelPageController.delegate = self; //相当于取得原来ViewController的引用 [self presentViewController:modelPageController animated:YES completion:^{ NSLog(@"modelPageController"); }];
4)、在ModalPageController需要的地方调用:
[self.delegate getInputText:@"hello Delegate"];
时间: 2024-10-29 19:09:56