iOS---block传值用法

来源:互联网 发布:mac 装google chrome 编辑:程序博客网 时间:2024/05/19 20:59

转载自:http://my.oschina.net/leejan97/blog/268536


http://blog.csdn.net/leikezhu1981/article/details/40018415


(2)第二种方法:使用Block作为property,实现两个页面之间传值,

先看看NextViewController文件中的内容,

?
1
2
3
4
5
6
7
8
9
10
11
12
//NextViewController.h 文件
@interface NextViewController : UIViewController
@property (nonatomic, copy) void (^NextViewControllerBlock)(NSString *tfText);
 
@end
//NextViewContorller.m 文件
- (IBAction)popBtnClicked:(id)sender {
    if (self.NextViewControllerBlock) {
        self.NextViewControllerBlock(self.inputTF.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

再来看看ViewController文件中的内容,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
- (IBAction)btnClicked:(id)sender
{
    NextViewController *nextVC = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil];
    nextVC.NextViewControllerBlock = ^(NSString *tfText){
        [self resetLabel:tfText];
    };
    [self.navigationController pushViewController:nextVC animated:YES];
}
#pragma mark - NextViewControllerBlock method
- (void)resetLabel:(NSString *)textStr
{
    self.nextVCInfoLabel.text = textStr;
}





/** ---------------------------------------------------------------------------*/










(3)block方式实现

block介绍:http://blog.csdn.net/totogo2010/article/details/7839061

链接一篇描述block回调挺有意思的文章: http://blog.csdn.net/mobanchengshuang/article/details/11751671

分析:

在B试图控制器中,定义一个block,参数为字符串

view sourceprint?
1.//SecondViewController.h
2.typedef void (^ablock)(NSString *str);
view sourceprint?
1.//SecondViewController.h
2. 
3.@property (nonatomic, copy) ablock block;

在B试图控制器中,当输入名字,点击对应的确定按钮后

view sourceprint?
01.- (IBAction)blockMethod:(id)sender {
02.if ([self notEmpty]) {
03.if (self.block) {
04.self.block(self.nameTextField.text);
05.[self dismissViewControllerAnimated:YES completion:nil];
06.}
07.}else{
08.[self showAlert];
09.}
10.}

在A试图显示,回调block

view sourceprint?
1.- (IBAction)showSecondWithBlock:(id)sender {
2.SecondViewController *second = [[SecondViewController alloc] initWithNibName:@'SecondViewController'bundle:nil];
3.[self presentViewController:second animated:YES completion:nil];
4.second.block = ^(NSString *str){
5.self.nameLabel.text = str;
6.};
7.}





0 0
原创粉丝点击