码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 使用Block进行逆传值

时间:2016-08-23 23:28:54      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

跟通知一样也是两个控制器,然后代码创建控件直接上代码

#import "ViewController.h"

#import "TwoViewController.h"

@interface ViewController ()

{

    UIButton *_nextBtn;

    UILabel *_showLabel;

 

}

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    [self show];

}

-(void)show{

    _nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

    

    [_nextBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

    [_nextBtn setTitle:@"下一个" forState:UIControlStateNormal];

    [_nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_nextBtn];

    

    

    _showLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 100,50)];

    [_showLabel setBackgroundColor:[UIColor greenColor]];

    

    [_showLabel setTextColor:[UIColor redColor]];

    [self.view addSubview:_showLabel];

    

    

    

    

}

-(void)nextBtnClick:(UIButton *)nextBtnClick{

    TwoViewController * two = [[TwoViewController alloc]init];

    two.block = ^(NSString * str){

        _showLabel.text = str;

    };

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

}

 

在TwoViewController.h中

#import <UIKit/UIKit.h>

typedef void (^MyBlock)(NSString *);

@interface TwoViewController : UIViewController

 

@property(nonatomic,copy)MyBlock block;

@end

 在TwoViewController.m中

#import "TwoViewController.h"

 

@interface TwoViewController ()

{

    UIButton *_backBtn;

    UITextField *_textField;

    

}

 

@end

 

@implementation TwoViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blueColor];

    [self shoulabel];

}

-(void)shoulabel{

    _backBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

    _backBtn.backgroundColor = [UIColor redColor];

    [_backBtn setTitle:@"shang" forState:UIControlStateNormal];

    [_backBtn addTarget:self action:@selector(shangBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_backBtn];

    _textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 400, 250, 35)];

    _textField.backgroundColor = [UIColor yellowColor];

    [self.view addSubview: _textField];

 

}

 

-(void)shangBtnClick:(UIButton *)shangBtn{

[self dismissViewControllerAnimated:YES completion:^{

    if (self.block) {

        self.block(_textField.text);

    }

    

}];

 

 

}

 

技术分享

技术分享

技术分享

 

 

技术分享

 

 这样就进行了简单的传值

 

iOS 使用Block进行逆传值

标签:

原文地址:http://www.cnblogs.com/hb201411/p/5801023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!