通过协议来实现ViewController之间的消息回传
正向传递肯定谁都会用,可是回传就要用到协议了。
1.建立一个.h文件,用来定义协议。
#import
@class UserEntity;
@protocol PassValueDelegate
-(void)passValue:(UserEntity *)value;
@end
2.在主ViewController上实现协议
这是.h文件:
#import
#import "PassValueDelegate.h"
//第一个窗口遵守PassValueDelegate
@interface ViewController : UIViewController
@interface ViewController : UIViewController
@end
这是.m文件:
//实现协议,在第一个窗口显示在第二个窗口输入的值,类似Android中的onActivityResult方法
-(void)passValue:(UserEntity *)value
{
self.nameLabel.text = value.userName;
self.ageLabel.text = [NSString stringWithFormat:@"%d",value.age];
self.gendarLabel.text = value.gendar;
}
self.nameLabel.text = value.userName;
self.ageLabel.text = [NSString stringWithFormat:@"%d",value.age];
self.gendarLabel.text = value.gendar;
}
3.实现协议,在第一个窗口在控制台弹出在第二个窗口输入的值
-(void)passValue:(NSString *)value
{
NSLog(value);
}
4.在进入第二个界面的按钮的Action上写入:
//点击进入第二个窗口的方法
- (IBAction)openBtnClicked:(id)sender {
SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
//设置第二个窗口中的delegate为第一个窗口的self
secondView.delegate = self;
[self.navigationController pushViewController:secondView animated:YES];
[secondView release];
}
SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
//设置第二个窗口中的delegate为第一个窗口的self
secondView.delegate = self;
[self.navigationController pushViewController:secondView animated:YES];
[secondView release];
}
5.在第二个窗口中声明一个NSObject对象,该对象遵守PassValueDelegate协议。
#import "PassValueDelegate.h"
@interface SecondViewController : UIViewController
//这里用assign而不用retain是为了防止引起循环引用。
@property(nonatomic,assign) NSObject *delegate;
#import "PassValueDelegate.h"
@interface SecondViewController : UIViewController
//这里用assign而不用retain是为了防止引起循环引用。
@property(nonatomic,assign) NSObject *delegate;
@end
6.设置回传按钮方法:
- (IBAction)okBtnClicked:(id)sender {
//通过委托协议传值
[self.delegate passValue:@“这是第二个界面的按钮按下的动作!"];
//退回到第一个窗口
[self.navigationController popViewControllerAnimated:YES];
- (IBAction)okBtnClicked:(id)sender {
//通过委托协议传值
[self.delegate passValue:@“这是第二个界面的按钮按下的动作!"];
//退回到第一个窗口
[self.navigationController popViewControllerAnimated:YES];
[userEntity release];
}
这样就实现了消息回传。
评论
发表评论