属性、协议、Block传值

来源:互联网 发布:康师傅 解散 知乎 编辑:程序博客网 时间:2024/06/06 08:38

属性传值

用于前一页给后一页传值

首先先在第二个页面上定义一个属性  用于接收外部传给自己的值

例如:

第二个页面.h

@property (nonatomic, copy) NSString *string;

然后在第一页面中给定义的属性附需要的值

例如:

第一个页面.m

    SecondViewController *secondVC = [[SecondViewController alloc] init];        // 给第二个视图控制器的 属性附值 (获取button的title)    secondVC.string = button.currentTitle;    [self.navigationController pushViewController:secondVC animated:YES];    [secondVC release];

最后就可以在第二个页面使用传过来的值

例如:

第二个页面.m

label.text = self.string;


协议传值

用于后一页给前一页传值

1.协议传值 协议由后面的视图控制器制定

第二个页面.h

@protocol SecondDelegate <NSObject>// 传值协议的方法需要带一个或多个参数- (void)passValueWithString:(NSString *)string;@end

2.设置自己的代理人属性

第二个页面.h

@interface SecondViewController : UIViewController@property (nonatomic, assign) id<SecondDelegate>  delegate;@end


3.让自己的代理人调用协议方法

比如说点击第二页的button 把button上的title传到第一页的label上

第二个页面.m

- (void)buttonClicked:(UIButton *)button{    // 3.让自己的代理人 调用 协议方法    [self.delegate passValueWithString:button.currentTitle];    [self.navigationController popViewControllerAnimated:YES];}

4.由第一个viewController 签订第二个viewController的协议

第一个页面.h

@interface FirstViewController : UIViewController <SecondDelegate>@end

5.给第二个viewController指定代理人

第一页面.m

secondVC.delegate = self;

6.实现协议方法

第一个页面.m

- (void)passValueWithString:(NSString *)string{   NSLog(@"从第二个viewController传来的值: %@", string);}

Block传值

用于第二个页面给第一个页面传值

第二页面.h

// 重定义一个Block的类型typedef void (^BL)(UIColor *color);@interface SecondViewController : UIViewController// 1.定义一个block属性 一定要使用copy特性@property(nonatomic, copy) BL block;@end
第二页面.m
- (void)buttonClicked1:(UIButton *)button{    // 2.在合适的地方执行 block代码    self.block([UIColor redColor]);        [self.navigationController popViewControllerAnimated:YES];}
第一页面.m
- (void)buttonClicked:(UIButton *)button{    // 3.在第一个页面中定义一个block 确定需要进行的操作    void (^changeColorBlock)(UIColor *color) = ^(UIColor *color) {        // 改变颜色        self.view.backgroundColor = color;            };            SecondViewController *secondVC = [[SecondViewController alloc] init];    // 4.给第二个页面的block赋值    secondVC.block = changeColorBlock;            [self.navigationController pushViewController:secondVC animated:YES];    [secondVC release];}





0 0