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

IOS学习 Notification 用通知传值

2016-03-04 14:41 495 查看
#import <UIKit/UIKit.h>

#import "SecondViewController.h"

#define kCLTN @"ChangLabelTextNotification"
//通知名

#define VIEW_WIDTH self.view.bounds.size.width

#define VIEW_HEIGHT self.view.bounds.size.height

@interface HomeViewController :
UIViewController

@end

@implementation HomeViewController

- (void)viewDidLoad {

[super
viewDidLoad];

UIButton *btn = [[UIButton
alloc]initWithFrame:CGRectMake(VIEW_WIDTH/2-50,
300, 100,
40)];

[btn setTitle:@"present"
forState:UIControlStateNormal];

btn.tintColor = [UIColor
whiteColor];

btn.backgroundColor = [UIColor
purpleColor];

[btn addTarget:self
action:@selector(click)
forControlEvents:UIControlEventTouchUpInside];

[self.view
addSubview:btn];

UILabel *Label = [[UILabel
alloc]initWithFrame:CGRectMake(VIEW_WIDTH/2-100,
160, 200,
40)];

Label.backgroundColor = [UIColor
orangeColor];

Label.text = @"yihong";

Label.tag = 102;

[self.view
addSubview:Label];

//向数据中心了注册了一个通知,ChangLabelTextNotification

[[NSNotificationCenter
defaultCenter]addObserver:self
selector:@selector(changLabelText:)
name:kCLTN
object:nil];

}

//传值设置

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

//根据tag查找label

UILabel *label = (UILabel *)[self.view
viewWithTag:102];

label.text = notification.object;

}

//页面跳转

- (void)click {

SecondViewController *secondVC = [[SecondViewController
alloc]init];

[self
presentViewController:secondVC animated:YES
completion:^{NSLog(@"present");}];

}

#import "HomeViewController.h"

@interface SecondViewController :
UIViewController

{

@private

UITextField *_textField;

}

@end

@implementation SecondViewController

- (void)viewDidLoad {

[super
viewDidLoad];

// Do any additional setup after loading the view.

_textField = [[UITextField
alloc]initWithFrame:CGRectMake(VIEW_WIDTH/2-100,
160,
200, 40)];

_textField.borderStyle =
UITextBorderStyleRoundedRect;

[self.view
addSubview:_textField];

UIButton *btn = [[UIButton
alloc]initWithFrame:CGRectMake(VIEW_WIDTH/2-50,
300, 100,
40)];

[btn setTitle:@"dismiss"
forState:UIControlStateNormal];

[btn addTarget:self
action:@selector(dismiss)
forControlEvents:UIControlEventTouchUpInside];

btn.backgroundColor = [UIColor
purpleColor];

btn.layer.cornerRadius =
6;

[self.view
addSubview:btn];

}

- (void)dismiss{

//监听homeVC上的通知

[[NSNotificationCenter
defaultCenter]postNotificationName:kCLTN
object:_textField.text];

//模态视图返回主页面

[self
dismissViewControllerAnimated:YES
completion:^{

NSLog(@"dismiss");}];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: