Thursday 19 December 2013

Notification Demo example in iPhone


ViewController.h


#import <UIKit/UIKit.h>

@class MyViewController;

@interface ip21ViewController : UIViewController

@property (nonatomic, retain) MyViewController *myvc;

@end

ViewController.m

 

#import "MyViewController.h"
@synthesize myvc;
- (void)viewDidLoad
{
    [super viewDidLoad];

    myvc = [[MyViewController alloc] init];
    myvc.view.frame = CGRectMake(60, 60, myvc.view.frame.size.width, myvc.view.frame.size.height);
    [self.view addSubview:myvc.view];
   
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didColorChangeNotification:)
                                                 name:@"ColorChangeNotification"
                                               object:nil];
}

- (void)didColorChangeNotification:(NSNotification *)aNotification
{
    if([aNotification.name isEqualToString:@"ColorChangeNotification"])
    {
        NSDictionary *dict = [aNotification userInfo];
       
        int c = [[dict objectForKey:@"Color"] integerValue];
       
        if(c == 1)
            self.view.backgroundColor = [UIColor redColor];       
        else if(c == 2)
            self.view.backgroundColor = [UIColor greenColor];
        else if(c == 3)
            self.view.backgroundColor = [UIColor blueColor];
        else
            self.view.backgroundColor = [UIColor grayColor];
    }
}

MyViewController.h


#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController

- (IBAction)buttoCLicked:(UIButton *)sender;

@end

MyViewController.m

 

- (IBAction)buttoCLicked:(UIButton *)sender
{
    NSDictionary *info = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d", sender.tag], @"Color", nil];
       
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ColorChangeNotification" object:nil userInfo:info];
}

No comments:

Post a Comment

Comment