首页 > 移动平台 > 详细

iOS学习-1.代理传值

时间:2016-03-21 01:37:15      阅读:252      评论:0      收藏:0      [点我收藏+]

代理的目的是改变或传递控制链。允许一个类在某些特定时刻通知到其他类,而不需要获取到那些类的指针。可以减少框架复杂度。?另外一点,代理可以理解为java中的回调监听机制的一种类似

优点:1、避免子类化带来的过多的子类以及子类与父类的耦合
         2、通过委托传递消息机制实现分层解耦

通过在A界面输入一段字符,在B界面的Label中显示的例子来说明

1.首先在A界面定义协议与方法

#import <UIKit/UIKit.h>
//定义协议与方法
@protocol viewDelegate <NSObject>
-(void)passText:(NSString *)text;
@end @interface ViewController : UIViewController //定义一个委托变量 @property(nonatomic,weak)id<viewDelegate>delagate; @end

2.A界面的实现文件

#import "ViewController.h"
#import "ViewController1.h"
@interface ViewController ()

@property(nonatomic,strong)UITextField *fid;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(Click) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    _fid = [[UITextField alloc]initWithFrame:CGRectMake(100, 300, 100, 100)];
    _fid.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_fid];
}
//点击事件
-(void)Click
{
    ViewController1 *view = [[ViewController1 alloc]init];
    
    self.delagate = view;
    
    [self.delagate passText:_fid.text];
    
    [self.navigationController pushViewController:view animated:YES];
}

3.到了B界面的头文件

#import <UIKit/UIKit.h>
#import "ViewController.h"
//添加代理
@interface ViewController1 : UIViewController<viewDelegate>

@end

4.B界面的实现文件

#import "ViewController1.h"

@interface ViewController1 ()
@property(nonatomic,strong)UITextField *field;
@end

@implementation ViewController1
//实现代理方法
-(void)passText:(NSString *)text
{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    _field = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    _field.backgroundColor = [UIColor redColor];
    [self.view addSubview:_field];
    //传值
    _field.text = text;
}

然后运行输入-跳转-显示,就行了

 

iOS学习-1.代理传值

原文:http://www.cnblogs.com/asamu/p/5300335.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!