【委托delegate】界面传值


使用委托delegate传递参数的方法和 block有点类似。


委托是指给一个对象提供机会,对另一对象中的变化做出反应或者相应另一个对象的行为。其基本思想是协同解决问题。

说白了就是:B 给A 一个机会(余额信息),当我没银行没钱了(余额为0),你就知道我没钱了 ,然后B给A打钱。

在程序中:一般情况下

1.委托需要做的工作有:

     1.1定义协议与方法 (@protocol .......)

    1.2声明委托变量      (@property (nonatomic,weak)id<SecondViewDelegate>delegate;

     1.3设置代理            (self.delegate=...)

     1.4通过委托变量调用委托方法

2.代理需要做的工作有:

     2.1遵循协议           (@interface ViewController :UIViewController<SecondViewDelegate>)

     2.2实现委托方法   





  1   如果想把信息从B传给A

  2  那么B就是委托方,A就是代理方

  3  通过B提出委托,A遵守协议,并且实现代理方法。



 1 B提出委托


1 首先在B界面 SecondViewController.h定义委托


#import <UIKit/UIKit.h>

//BA传参数,B是委托方,A是代理方。

//B提出委托也就是 协议。

//A遵守协议委托,并实现代理方法。

@protocol SecondViewDelegate

- (void)showName:(NSString *)nameString;

@end


@interface SecondViewController : UIViewController


@property (nonatomic,weak)id<SecondViewDelegate>delegate;



@end




3在SecondViewControler.m 的按钮里面设置事件,橙色字体就是设置值。




#import <UIKit/UIKit.h>

//BA传参数,B是委托方,A是代理方。

//B提出委托也就是 协议。

//A遵守协议委托,并实现代理方法。

@protocol SecondViewDelegate

- (void)showName:(NSString *)nameString;

@end


@interface SecondViewController : UIViewController


@property (nonatomic,weak)id<SecondViewDelegate>delegate;



@end




   2  遵守委托协议


4 在ViewController.h里面,也就是主页 继承协议。


#import <UIKit/UIKit.h>

#import "SecondViewController.h"

@interface ViewController : UIViewController<SecondViewDelegate>



@end



5  ViewController.m


#import "ViewController.h"


@interface ViewController ()


@property (nonatomic,strong) UILabel *nameLabel;

@end


@implementation ViewController


- (void)viewDidLoad

{

    [super viewDidLoad];


    //设置跳转按钮

    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(20, 180, 130, 50)];

    [btn setTitle:@"跳转" forState:UIControlStateNormal];

    [btn setTintColor:[UIColor orangeColor]];

    btn.backgroundColor=[UIColor blackColor];

    [btn addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

  

    self.nameLabel=[[UILabel alloc] initWithFrame:CGRectMake(20, 80, 130, 50)];

    self.nameLabel.backgroundColor=[UIColor orangeColor];

    [self.view addSubview:self.nameLabel];

    

}


- (void)clickAction

{

    SecondViewController *one=[[SecondViewController alloc]init];

    [self presentViewController:one animated:YES completion:nil];

    //设置代理,它就是代理方。    !!!很关键。

    one.delegate = self;


}


#pragma mark 实现传值协议方法


- (void)showName:(NSString *)nameString

{

    self.nameLabel.text=nameString;

}


@end


  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值