一:两个view之间的数据相互传递。
1)这里两个view间切换主要用到的是每个类对象固有的属性(modalTransitionStyle)来设置过渡模式(也就是过渡(切换)到别的界面)。
2)还会用到委托(delegate)来响应事件方法。
3)要特别注意协议delegate:
[plain] view plaincopy
@protocol delegate <NSObject>
-(void)myupdata:(NSString *)str;
@end
在此程序中的作用:是从视图2(MyModalTransition (定义一个id 类型遵循上诉协议的属性:mydelegate 。mydalegate会得到视图1类,从而调用其实现的方法。))返回到视图1(MyObserver(遵循上诉协议实现其myupdata方法))的重要渠道。
二:新建程序:
第一个view
MyObserver.h
[plain] view plaincopy
#import <UIKit/UIKit.h>
#import "MyClass.h"
#import "MyModalTransition.h"
@interface MyObserver : UIViewController <delegate> {
UITextField *mytext01;
}
@property(retain) MyClass *myclass;
//定义另一个类MyModalTransition的属性
@property(nonatomic,retain) MyModalTransition *mymtra;
@property (nonatomic, strong) IBOutlet UITextField *mytext01;
-(void)myupdata:(NSString*) str;- (IBAction)btnpress:(id)sender;
-(void)exit;
@end
MyObserver.m
[plain] view plaincopy
#import "MyObserver.h"
@implementation MyObserver
@synthesize mytext01;
@synthesize mymtra;
- (void)viewDidLoad
{
//点击屏幕键盘的return键时,键盘响应exit方法,放弃第一响应者退出
[self.mytext01 addTarget:self action:@selector(exit) forControlEvents:UIControlEventEditingDidEndOnExit];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(void)myupdata:(NSString *)str{
self.mytext01.text=str;
//放弃过渡模式,开始开始显示第一个view
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)btnpress:(id)sender {
self.mymtra=[[MyModalTransition alloc] init];
//定义模型过渡样式
mymtra.modalTransitionStyle=UIModalTransitionStylePartialCurl;
//mymtra.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
//数据传递
mymtra.message=self.mytext01.text;
//把当前类self传给另一个视图的委托
mymtra.mydelegate=self;
//呈现模型
[self presentModalViewController:mymtra animated:YES];
}
-(void)exit{
//放弃第一响应者身份
[self resignFirstResponder];
}
第二个view
MyModalTransition.h
[plain] view plaincopy
#import <UIKit/UIKit.h>
//在这定义协议的原因是:这样mydelegate属性遵循协议的时候本身就有了myupdata方法,其实现部分就是在上一个视图MyObserver里。当mydelegate获得MyObserver时就可以调用这个方法了。
@protocol delegate <NSObject>
-(void)myupdata:(NSString *)str;
@end
@interface MyModalTransition : UIViewController {
UITextField *mytext02;
}
//遵循delegate协议就拥有了其myupdata方法
@property(assign) id <delegate>mydelegate;
@property (nonatomic, strong) IBOutlet UITextField *mytext02;
@property(copy) NSString *message;
- (IBAction)btnbackpress:(id)sender;
@end
MyModalTransition.m
[plain] view plaincopy
#import "MyModalTransition.h"
@implementation MyModalTransition
@synthesize mytext02;
@synthesize mydelegate;
@synthesize message;
//点击按钮
- (IBAction)btnbackpress:(id)sender {
NSString *str=mytext02.text;
//值传递
[self.mydelegate myupdata:str];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
self.mytext02.text=message;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
运行结果: