iOS—协议传值

协议传值,反向传值,将值从第二个界面传回第一个界面。

协议传值的六步:
  1. 声明协议,自定义声明一个协议方法
  2. 声明代理人属性
  3. 遵守协议
  4. 设置代理
  5. 实现协议方法
  6. 执行协议方法

代码:

//SecondViewController.h 文件中

#import <UIKit/UIKit.h>
//第1步
//声明协议
@protocol  PassValueDelegate <NSObject>
//自定义协议方法
- (void)passContent:(NSString *)content;

@end


@interface SecondViewController : UIViewController
@property UITextField *textfield;
//第2步
//声明代理人属性
@property id<PassValueDelegate> delegate;

@end
//FirstViewController.m文件中
#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()
//第3步 签订协议
<PassValueDelegate>

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btn.frame = CGRectMake(140, 210, 100, 40);
    [_btn setTitle:@"下一页" forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(pressNext) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btn];
    _content = [[UILabel alloc] initWithFrame:CGRectMake(140, 160, 200, 40)];
    _content.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_content];
    
    
    
}

- (void)pressNext {
    SecondViewController *secondView = [[SecondViewController alloc] init];
    //第四步 设置代理
    secondView.delegate = self;
    [self presentViewController:secondView animated:YES completion:nil];
    
}

//第五步 实现协议方法
- (void)passContent:(NSString *)content {
    _content.text = content;
}
//在SecondViewController.m 文件中
#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _textfield = [[UITextField alloc] initWithFrame:CGRectMake(50, 130, 300, 40)];
    _textfield.borderStyle = UITextBorderStyleLine;
    [self.view addSubview:_textfield];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    backBtn.frame = CGRectMake(100, 210, 100, 40);
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(pressBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
}
- (void)pressBack {
    //第6步  执行协议方法
    [self.delegate passContent:_textfield.text];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

效果图:
第一个界面,如图

点击下一页,切换到第二个界面,在第二个界面的文本框输入内容,如图

1

点击返回,第一个界面显示如下:

2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值