Block传值 反向传值

反向传值可以用单例、代理和Block,当然SEL也可以,下面简单介绍一下Block传值,直接上代码

1.新建一个single view工程


2.在AppDelegate.m中

    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    
    self.viewController.title = @"Block传值";
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    
    self.window.rootViewController = nc;


3.ViewController.h

@interface ViewController : UIViewController {
    UILabel *valueLabel;//用来接收SecondViewController传回的值
}
@end

4.实现ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
    [self.view addSubview:valueLabel];
    [valueLabel release];
    
    UIBarButtonItem *nextBtn = [[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextClick)];
    self.navigationItem.rightBarButtonItem = nextBtn;
    [nextBtn release];
}

- (void)nextClick
{
    SecondViewController *svc = [[SecondViewController alloc] init];
    svc.backValue = ^(NSString *strValue) {//设置SecondViewController里边的block属性,这是本程序的关键
        valueLabel.text = strValue;
    };
    [self.navigationController pushViewController:svc animated:YES];
    [svc release];
}

5.SecondViewController.h

@interface SecondViewController : UIViewController

@property (nonatomic, copy) void (^backValue)(NSString *strValue);
@property (nonatomic, retain) UITextField *text;

@end

6.实现SecondViewController.m

@implementation SecondViewController

@synthesize backValue;
@synthesize text;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    text = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 300, 40)];
    text.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:text];
    [text release];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(10, 110, 60, 30);
    [btn setTitle:@"返回" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)btnClick
{
    self.backValue(self.text.text);//调用block方法
    [self.navigationController popViewControllerAnimated:YES];
}

@end

效果图                                

返回之后:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值