用Notifaction正向传值,将A界面的值传到B界面。在A类中发送一个通知,在B类中注册一个通知。
1、A类中的代码如下:
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
@property (retain,nonatomic) UITextField *textField;
@end
@implementation FirstViewController
@synthesize textField;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Notifaction正向传值";
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, 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];
}
- (void)viewDidDisappear:(BOOL)animated {
//发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"flash" object:self userInfo:@{@"name":textField.text}];
}
- (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) UILabel *label;
@end
@implementation SecondViewController
@synthesize label;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
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, 150, self.view.frame.size.width-20, 35)];
btn.backgroundColor = [UIColor grayColor];
[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 {
[self.navigationController popViewControllerAnimated:YES];
}
@end
3、效果截图如下:
4 、Demo下载地址 : http://download.csdn.net/detail/u010545480/8909563