关于通知传值--NSNotification

先创建两个UIViewController(系统自带算一个)

从SecondView向ViewController传值:

#import "ViewController.h"
#import "SecondViewController.h"
@interface  ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIButton *button =[UIButton buttonWithType:UIButtonTypeContactAdd];
    button.frame =CGRectMake(100, 100, 30, 30);
    [button addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(20, 200, 300, 100)];
    label.backgroundColor=[UIColor grayColor];
    label.font=[UIFont systemFontOfSize:25];
    label.tag=100;
    label.textAlignment=NSTextAlignmentCenter;
    
    [self.view addSubview:label];
   //接受通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receive:) name:@"tongzhi" object:nil];
    
}
-(void)receive:(NSNotification *)noti
{
    //需要把通知的信息给取出来
    NSString *str =noti.userInfo[@"str"];


    UILabel *label =(UILabel *)[self.view viewWithTag:100];
    label.text=str;
}

-(void)btnClicked
{
    SecondViewController *secVC = [[SecondViewController alloc]init];
    [self presentViewController:secVC animated:YES completion:nil];
}


#import "SecondViewController.h"

@interface SecondViewController ()<UITextFieldDelegate>

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    UITextField *textFiled =[[UITextField alloc]initWithFrame:CGRectMake(20, 200, 300, 100)];
    textFiled.backgroundColor=[UIColor orangeColor];
    textFiled.placeholder=@"this is textFiled!";
    [textFiled becomeFirstResponder];
    textFiled.delegate=self;
    
    [self.view addSubview:textFiled];
 
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
    /**
     *  通知传值,,邮件等。。。。
     */
    //创建通知
    NSNotification *noti =[[NSNotification alloc]initWithName:@"tongzhi" object:self userInfo:@{@"str":textField.text}];
    //发送通知
    [[NSNotificationCenter defaultCenter]postNotification:noti];
    
    return YES;
}

好了,就这么多,主要代码已经在其中用不同的颜色标记。



转载于:https://my.oschina.net/QGH1128/blog/513992

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值