#import <UIKit/UIKit.h>
//1.协议传值
// 协议由后面的视图控制器制定
@protocol secondDelegate <NSObject>
//协议的方法需要带一个或多个参数
- (void)passValueWithString:(NSString *)string;
@end
@interface secondViewController : UIViewController
//2.设置自己的 代理人 属性
@property (nonatomic, assign) id<secondDelegate> delegate;
@end
- (void)buttonAction:(UIButton *)button
{
NSLog(@"suck");
//3.让自己的代理人 调用 协议方法
[self.delegate passValueWithString:button.currentTitle];
[self.navigationController popViewControllerAnimated:YES];
}
在第二个视图控制器的 .h 文件的具体方法中 让自己的代理人 调用 协议方法
- (void)buttonAction:(UIButton *)button
{
NSLog(@"suck");
//3.让自己的代理人 调用 协议方法
[self.delegate passValueWithString:button.currentTitle];
[self.navigationController popViewControllerAnimated:YES];
}
#import <UIKit/UIKit.h>
#import "secondViewController.h"
//4.由第一个viewController 签订 第二个viewController的协议
@interface mainViewController : UIViewController <secondDelegate>
@end
===================================================
在第一个视图控制器的 .h 文件里的具体方法中实现 以下:
- (void)buttonAction:(UIButton *)button
{
secondViewController *secondVC = [[secondViewController alloc]init];
//5.给第二个viewController 指定代理人
[secondVC setDelegate:self];
[self.navigationController pushViewController:secondVCanimated:YES];
[secondVC release];
}
//6.实现协议的方法
- (void)passValueWithString:(NSString *)string
{
NSLog(@"从第二个viewController传来的值: %@", string);
UILabel *label = (UILabel *)[self.view viewWithTag:50];
[label setText:string];
}