协议传值

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

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

//协议传值的第一步
// 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值