关闭

[置顶] iOS block传值(逆传)

标签: iOSObjective-C界面苹果
889人阅读 评论(0) 收藏 举报
分类:

block是个好东西,是苹果官方推荐的一种方法,效率高,代码简单,今天用block主要是做一个简单传,暂时不对block详细介绍,关于__block的用法,后期会一一介绍;

接下来,通过一个block,将 SecondViewController 的数值传给  FirstViewController ;

FirstViewController.m

#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()<UITextFieldDelegate>
{
    //切换到下一个界面
    UIButton *_btn;
    
    //现实从 SecondViewController 传过来的值
    UILabel *_label;
}

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor: [UIColor yellowColor]];
    
    [self layouUI];
    
}

-(void)layouUI
{
//    创建lable
    _label=[[UILabel alloc] initWithFrame:CGRectMake(100, 60, 120, 40)];
    _label.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_label];
    
    //切换到 SecondViewController
    _btn=[[UIButton alloc]initWithFrame:CGRectMake(100, 220, 120, 40)];
    [_btn setBackgroundColor:[UIColor cyanColor]];
    [_btn addTarget:self action:@selector(dobtn) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_btn];
}

-(void)dobtn
{
    SecondViewController *second=[[SecondViewController alloc]init];
    second.mb=^(NSString *str){
        _label.text=str;
    };
    [self.navigationController pushViewController:second animated:YES];
    
}
@end


运行结果如下图:



创建第二个控制器:

SecondViewController.h

#import <UIKit/UIKit.h>

//定义block
typedef void(^Myblock)(NSString *str);

@interface SecondViewController : UIViewController

@property(strong,nonatomic)Myblock mb;


@end


SecondViewController.m

#import "SecondViewController.h"

@interface SecondViewController ()
{
    UIButton *_btn;
    UILabel *_label;
    UITextField *_textField;
}

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor purpleColor]];
    [self layouUI];
}
-(void)layouUI
{
    //    创建一个textfield
    _textField=[[UITextField alloc]initWithFrame:CGRectMake(100, 140, 120, 40)];
    _textField.borderStyle=UITextBorderStyleLine;
    [self.view addSubview:_textField];

    
    _btn=[[UIButton alloc]initWithFrame:CGRectMake(100, 220, 120, 40)];
    [_btn setBackgroundColor:[UIColor cyanColor]];
    [_btn addTarget:self action:@selector(dobtn) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_btn];
}
-(void)dobtn
{
//    在这里调用block
    self.mb(_textField.text);
    [self.navigationController popViewControllerAnimated:YES];
}

@end


然后在 _textField 写入文字,例如写 welcome to air

如下图:



在第一个控制器上的label就会显示出来第二控制器上写的字符串;

如下图:



如果转载请注明转于:AirZilong的博客

3
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65351次
    • 积分:1110
    • 等级:
    • 排名:千里之外
    • 原创:43篇
    • 转载:3篇
    • 译文:1篇
    • 评论:31条
    文章分类
    最新评论