Reputation: 34370
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.
Upvotes: 1
Views: 450
Reputation: 2457
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.
Upvotes: 2
Reputation: 8954
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]
Upvotes: 0