您的位置:首页 > 移动开发 > IOS开发

iOS中使用Block反响传值的用法

2015-11-14 10:51 531 查看
方向传值,用block传值要比用代理传值简单多,并且代码简单。
有一个A页面和B页面,B页面的值传给A页面,这就是用Block方向传值。
下面直接上代码
A页面代码
UIButton * playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playButton.frame = CGRectMake(100, 220, 100, 80);
    [playButton setTitle:@"选择播放视频" forState:UIControlStateNormal];
    [playButton setBackgroundColor:[UIColor grayColor]];
    [playButton addTarget:self action:@selector(playVideoGo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playButton];
    
    self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 320, 100, 30)];
    self.textLabel.backgroundColor = [UIColor greenColor];
    [self.textLabel setText:@"回调传值"];
    [self.view addSubview:self.textLabel];


- (void)playVideoGo {
    playVideoViewController * vc = [[playVideoViewController alloc] init];
    vc.returnBlock = ^(NSString * showText){
        NSLog(@"----------%@",showText);
        self.textLabel.text = showText;
    };
    [self presentViewController:vc animated:YES completion:nil];
    //[self.navigationController pushViewController:vc animated:YES];
}


B页面代码如下:
在.h文件里申明一个Block
typedef void (^ReturnTextBlock)(NSString * showText);
在.m文件中

self.inputFiled = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
    self.inputFiled.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.inputFiled];
    
    
    
    UIButton * playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playButton.frame = CGRectMake(100, 220, 100, 80);
    [playButton setTitle:@"回调" forState:UIControlStateNormal];
    [playButton setBackgroundColor:[UIColor grayColor]];
    [playButton addTarget:self action:@selector(playVideoBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playButton];


-(void)playVideoBack {
    self.returnBlock(self.inputFiled.text);
    [self dismissViewControllerAnimated:YES completion:nil];
    //[self.navigationController popViewControllerAnimated:YES];
}


这样即可完成页面反响传值。。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: