协议传值

来源:互联网 发布:python教程 图灵 编辑:程序博客网 时间:2024/06/07 15:13

协议传值是针对从后往前传值

先要自己定义协议 并且写协议方法 通过协议方法进行传值

//协议传值的第一步// 1.声明一份协议@protocol SecondViewControllerDelegate <NSObject>//协议方法-(void)changeValue:(NSString *)value;@end//在SecondViewController中声明协议@interface SecondViewController : UIViewController//2.设置代理人的属性@property(nonatomic,assign)id<SecondViewControllerDelegate>delegate;@end

属性传值在.m文件中需要写的内容,控件的基本内容不再详述

@interface SecondViewController ()//一个textfield,一个button@property(nonatomic,retain)UITextField *textField;@property(nonatomic,retain)UIButton *button;@end@implementation SecondViewController-(void)dealloc{    [_button release];    [_textField release];    [super dealloc];}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    [self.view addSubview:self.textField];    self.view.backgroundColor = [UIColor lightGrayColor];    self.button = [UIButton buttonWithType:UIButtonTypeSystem];    [self.button setTitle:@"返回" forState:UIControlStateNormal];    [self.view addSubview:self.button];    [self.button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];}//点击返回//协议的触发条件是点击按钮,所以在这里面进行协议传值的第三步//3.设置代理人执行的协议方法-(void)click:(UIButton *)button{    [self.navigationController popToRootViewControllerAnimated:YES];//传的值是自定义的textField里面的内容    [self.delegate changeValue:self.textField.text];   }

实现协议传值

#import "SecondViewController.h"//4.签订协议@interface MainViewController ()<SecondViewControllerDelegate>@property(nonatomic,retain)UILabel *lable;@property(nonatomic,retain)UIButton *button;@end@implementation MainViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    self.lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 150, 40)];    [self.lable release];    self.button = [UIButton buttonWithType:UIButtonTypeSystem];    [self.button setTitle:@"下一页" forState:UIControlStateNormal];    [self.button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];    self.navigationController.navigationBar.translucent = NO;   }-(void)click:(UIButton *)button{//push下一页    SecondViewController *secVC = [[SecondViewController alloc]init];    [self.navigationController pushViewController:secVC animated:YES];    [secVC release];//5.设置代理人    secVC.delegate = self;}//6.实现协议方法-(void)changeValue:(NSString *)value{    NSLog(@"%@",value);//协议传的值赋值给自定义的label    self.lable.text = value;}
0 0