block在两个页面的传值

一直知道block有反向传值的功能,自己做了个测试。

第一个页面有一个label,第二个页面有个UITextField。

当在UITextField输入值后,点击导航栏上的back按钮,可以将UITextField上面的值反回到第一个页面的label上。

#import"ViewController.h"

#import"SecondViewController.h"

@interfaceViewController()

{

UILabel*label;

}

@end

@implementationViewController

- (void)viewDidLoad {

[superviewDidLoad];

label= [[UILabelalloc]initWithFrame:CGRectMake(100,100,100,50)];

label.backgroundColor= [UIColorwhiteColor];

[self.viewaddSubview:label];

self.navigationItem.rightBarButtonItem= [[UIBarButtonItemalloc]initWithTitle:@"next"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(next:)];

}

-(void)next:(UIBarButtonItem*)sender{

SecondViewController*sVC= [[SecondViewControlleralloc]init];

[self.navigationControllerpushViewController:sVCanimated:YES];

sVC.block=^(NSString*string)

{

label.text= string;

returnstring;

};

第二个页面的.h

#import

//声明一个有返回值的名字叫sendValue的block

typedefNSString*(^sendValue)(NSString*) ;

@interfaceSecondViewController :UIViewController

//把block定义为属性

@property(nonatomic,strong)sendValueblock;

@end

.m

#import"SecondViewController.h"

@interfaceSecondViewController()

{

UITextField*textField;

}

@end

@implementationSecondViewController

- (void)viewDidLoad {

[superviewDidLoad];

textField= [[UITextFieldalloc]initWithFrame:CGRectMake(100,100,100,50)];

textField.backgroundColor= [UIColorwhiteColor];

[self.viewaddSubview:textField];

self.navigationItem.rightBarButtonItem= [[UIBarButtonItemalloc]initWithTitle:@"back"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(back:)];

}

-(void)back:(UIBarButtonItem*)sender{



self.block(textField.text);//调用block

[self.navigationControllerpopToRootViewControllerAnimated:YES];

}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • 为什么人容易在新年给自己制定目标呢?因为仪式感。适当的仪式感的确会给人一种不一样的feel,甚至重燃希望。 我也一...
    小小鹿乱撞阅读 170评论 0 0