IOS学习 Notification 用通知传值

来源:互联网 发布:淘宝被处罚了怎么办 编辑:程序博客网 时间:2024/06/13 12:55

#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 {

    [superviewDidLoad];

    

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

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

    btn.tintColor = [UIColorwhiteColor];

    btn.backgroundColor = [UIColorpurpleColor];

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

    [self.viewaddSubview:btn];

    

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

    Label.backgroundColor = [UIColororangeColor];

    Label.text = @"yihong";

    Label.tag = 102;

    [self.viewaddSubview:Label];

    

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

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(changLabelText:)name:kCLTNobject:nil];

}

//传值设置

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

    //根据tag查找label

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

    label.text = notification.object;

}


//页面跳转

- (void)click {

    SecondViewController *secondVC = [[SecondViewControlleralloc]init];

    [selfpresentViewController:secondVC animated:YEScompletion:^{NSLog(@"present");}];

}




#import "HomeViewController.h"


@interface SecondViewController : UIViewController

{

@private

    UITextField *_textField;

}

@end




@implementation SecondViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    

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

    _textField.borderStyle =UITextBorderStyleRoundedRect;

    [self.viewaddSubview:_textField];

    

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

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

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

    btn.backgroundColor = [UIColorpurpleColor];

    btn.layer.cornerRadius =6;

    [self.viewaddSubview:btn];

}


- (void)dismiss{

    //监听homeVC上的通知

    [[NSNotificationCenterdefaultCenter]postNotificationName:kCLTNobject:_textField.text];

    //模态视图返回主页面

    [selfdismissViewControllerAnimated:YEScompletion:^{

        NSLog(@"dismiss");}];

}

0 0