iOS - 页面之间传值的实现 - 代理

来源:互联网 发布:linux时钟同步设置 编辑:程序博客网 时间:2024/05/19 20:20

上篇文章记录了利用 block 实现页面之间的传值,这篇博客记录一下,利用代理实现从后往前的传值。

思路不再赘述(如果您看过上篇博客的话)。。。

首先,看 ViewController.m 中 :

#import "ViewController.h"

#import "FirstViewController.h"


@interface ViewController ()<ZJJPassNumberDelegate> {

    UILabel *_label;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    

    // 创建按钮

    UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];

    button.frame =CGRectMake(100,100, 100,50);

    button.backgroundColor = [UIColorlightGrayColor];

    [button setTitle:@"next"forState:UIControlStateNormal];

    [button addTarget:selfaction:@selector(buttonClick)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:button];

    

    // 创建label

    UILabel *label = [[UILabelalloc] init];

    label.frame =CGRectMake(210,100, 100,50);

    label.textColor = [UIColorredColor];

    label.backgroundColor = [UIColorcyanColor];

    [self.viewaddSubview:label];

    _label = label;

    

}


- (void)buttonClick {

    

    FirstViewController *first = [[FirstViewControlleralloc] init];

    // 注册代理(确定代理关系)

    first.delegate =self;

    [selfpresentViewController:firstanimated:YEScompletion:nil];

}


// 代理方法的实现

- (void)changeLabelTextWithTitle:(NSString *)title {

    _label.text = title;

}


然后,再看 FirstViewController.h 中 :

// 注册代理

@protocol ZJJPassNumberDelegate <NSObject>


// 声明一个代理方法

- (void)changeLabelTextWithTitle:(NSString *)title;


@end


@interface FirstViewController :UIViewController


// 注意,一定是assign

@property (assign,nonatomic)id <ZJJPassNumberDelegate> delegate;


@end



最后,看 FirstViewController.m 中 :


#import "FirstViewController.h"


@interface FirstViewController () {

    UITextField *_tf;

}


@end


@implementation FirstViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColorcyanColor];

    

    // 创建按钮

    UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];

    button.frame =CGRectMake(100,400, 100,50);

    button.backgroundColor = [UIColorlightGrayColor];

    [button setTitle:@"back"forState:UIControlStateNormal];

    [button addTarget:selfaction:@selector(backButtonClick)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:button];


    UITextField *tf = [[UITextFieldalloc] init];

    tf.frame =CGRectMake(210,400, 100,40);

    tf.backgroundColor = [UIColorwhiteColor];

    [self.viewaddSubview:tf];

    _tf = tf;

    

}


- (void)backButtonClick {

    

    if ([self.delegaterespondsToSelector:@selector(changeLabelTextWithTitle:)]) {

       

        [self.delegatechangeLabelTextWithTitle:_tf.text];


    }

    

    [selfdismissViewControllerAnimated:YEScompletion:nil];

}


OK,到此,利用代理实现从后往前传值的方法已经实现。。。


0 0
原创粉丝点击