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

4、iOS传值的方法-Notifaction反向传值

2015-07-17 16:43 417 查看
iOS传值,用Notifaction反向传值,将B界面的值传到A界面。在A界面注册一个通知,在B界面发送一个通知。

1、A类中的代码如下:

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()

@property (retain, nonatomic) UILabel *label;

@end

@implementation FirstViewController
@synthesize label;

- (void)viewDidLoad {
[super viewDidLoad];

self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Notifaction反向传值";

label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, 30)];
label.text = @"点击按钮";
[self.view addSubview:label];

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 200, self.view.frame.size.width-20, 35)];
btn.backgroundColor = [UIColor grayColor];
[btn setTitle:@"确定" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

//注册一个通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(flashString:) name:@"flash" object:nil];

}

- (void)flashString:(NSNotification *)notification {

NSDictionary *dict = [notification userInfo];
label.text = [dict objectForKey:@"name"];
}

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)btnClick:(id)sender {

SecondViewController *second = [[SecondViewController alloc] init];
[self.navigationController pushViewController:second animated:YES];

}

@end


2、B类中的代码如下:

#import "SecondViewController.h"

@interface SecondViewController ()

@property (retain,nonatomic) UITextField *textField;

@end

@implementation SecondViewController
@synthesize textField;

- (void)viewDidLoad {
[super viewDidLoad];

self.view.backgroundColor = [UIColor whiteColor];

textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 150, self.view.frame.size.width-20, 35)];
btn.backgroundColor = [UIColor grayColor];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}

- (void)btnClick:(id)sender {

//发送一个通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"flash" object:self userInfo:@{@"name":textField.text}];

[self.navigationController popViewControllerAnimated:YES];

}

@end


3、效果截图如下:


    


4、Demo下载地址 : http://download.csdn.net/detail/u010545480/8909569
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS 传值