使用NSNotification 来改变界面的颜色

本文详细介绍了NSNotification类在iOS开发中的使用方法,包括如何发送和接收通知,以及如何利用userInfo传递额外信息。通过示例代码展示了NSNotification在视图控制器间通信的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.关于NSNotification 的使用这个类实际就是一个通知中心,该对象有两个重要的成员变量:name 和object,还有一个用来传递更多信息的userInfo

 

/**************** Notifications ****************/

 

@interface NSNotification :NSObject <NSCopying, NSCoding>

 

- (NSString *)name;

- (id)object;

- (NSDictionary *)userInfo;

 

@end

该类有两个两种方法来传递信息:

 

+ (id)notificationWithName:(NSString *)aName object:(id)anObject;

+ (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

用第二个类方法可以传递更多的信息:

 

传递

 

 

 

 

 

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

@synthesize button;

 

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(reserve_notification:)name:@"Meth"object:nil];

    

    button=[[UIButtonalloc] initWithFrame:CGRectMake(20,60,100,35)];

    button.backgroundColor=[UIColorblueColor];

     self.view.backgroundColor=[UIColorwhiteColor];

    

    

    [buttonsetTitle:@"Changed Color"forState:UIControlStateNormal];

    [buttonsetTitleColor:[UIColorblackColor] forState:UIControlStateHighlighted];

    [buttonsetTitleShadowColor:[UIColorblueColor] forState:UIControlStateHighlighted];

    [buttonaddTarget:selfaction:@selector(sendNotification)forControlEvents:UIControlEventTouchDown];

    [self.view addSubview:button];   

}

 

-(void)sendNotification 

{

   

    NSLog(@"sendNotfication");

    NSDictionary *userInfo=[NSDictionarydictionaryWithObjectsAndKeys:@"user1",@"key1",@"user2",@"key2",nil];

    [[NSNotificationCenterdefaultCenter] postNotificationName:@"Meth"object:niluserInfo:userInfo];

}

 

-(void)reserve_notification:(NSNotification *)notify

{

 

 

NSLog(@"userInfo descrption %@",[userInfodescription]);

    self.view.backgroundColor=[UIColorredColor];

}

 

- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值