block在两个页面的传值
2016-03-02 本文已影响93人
七月上
一直知道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