Where to handle event of UIApplication subview

442 views Asked by At

While studying UIApplication, I find a way to add a view on top of all UIViewController.

  UIView *testView =  [[UIView alloc] initWithFrame:CGRectMake(40,40,250,250)];
    [testView setBackgroundColor:[UIColor redColor]];

    [[[UIApplication sharedApplication] keyWindow] addSubview:testView];

It is displaying correctly.

I am wondering if I created a menu with some buttons instead of testView. Where can i handle those events in AppDelegate or Current ViewController

If it is possible then tell me how to change text of any ViewController on clicking menu button.

I mean how to get the context of another ViewController and set its View Property from that button.

2

There are 2 answers

0
Unnati On

Yes, it is possible. You can add button and set it's action events. Then you may add Observer using NSNotificationCenter. Then you can receive notification about the button click in whichever UIViewController you want.

Here is the code:

add button like this:

UIButton *button =  [[UIButton alloc] initWithFrame:CGRectMake(40,40,250,250)];
[[[UIApplication sharedApplication] keyWindow] addSubview:button];
[button addTarget:self 
             action:@selector(doSomething) 
   forControlEvents:UIControlEventTouchUpInside];

Post notification in button event handler:

- (void)doSomething {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"buttonClicked" object:nil];
}

Receive the notification in another ViewController:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourmethod) name:@"buttonClicked" object:nil];

Then in 'yourmethod', you can change the text.

0
l0gg3r On

That's a very bad idea to add subviews to keyWindow, and after that retrieve current viewControllers. Probably you will make a hell. (Before iOS8 windows don't change bounds and orientations, now they change)

Instead of it, make a subclass of your root navigation controller.
Add subview's to self.view, and get active controller via [self.viewControllers lastObject]