Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Window's element visibility from a subclassed WebView

I'm trying to make a very simple app. It's just a super simple web browser with 3 pages. 3 webview, 2 hidden at all time.

I subclassed WebView to be able to catch keystroke events while focused. This part works.

Now I'd need to callback home and change the other WebViews' visibility when I press CMD+1, CMD+2, CMD+3 (1 would show first webview, hide 2 others, etc).

I tried to think about how to use delegates to achieve my goal, but my lack of knowledge is keeping me from finishing this simple app.

I also heard about NSNotification, my WebView could send a notification that my Window could catch and change the visibility of its children but I'm not sure how to achieve so either.

Anyone could point me in the right direction please?

TLDR; When a WebView catches a CMD+1 for example, I want to be able to call a method in the other WebViews to get them hidden.

Thanks and have a nice day!

like image 839
Tommy B. Avatar asked May 27 '13 19:05

Tommy B.


1 Answers

Using notifications: say where you catch the key stroke you have an NSString object containing some ID to identify the desired WebView (for example @"1" or @"2" etc), and every web view has a viewID property. So where you recieve the key stroke, you'd add:

[[NSNotificationCenter defaultCenter]
    postNotificationName:@"ChangeMyActiveWebView"
    object:newViewID  // <- contains string to identify the desired web view
];

Somewhere where your web view is initialized (for example -awakeFromNib or -init), you add this code:

[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(switchViewNotification:)
    name:@"ChangeMyActiveWebView"
    object:nil  // Means any object
];

Then implement the -switchViewNotification: method:

- (void)switchViewNotification:(NSNotification *)aNotification {

    NSString    *newViewID=[aNotification object];

    if([self.viewID isEqualToString:newViewID])
    {
        // show this web view
    }
    else
    {
        // hide this web view
    }
}

Final piece: you need to remove the observer when the web view goes away, so add this to your -dealloc method:

[[NSNotificationCenter defaultCenter]removeObserver:self];

That should do it.

like image 199
Gerd K Avatar answered Nov 19 '22 08:11

Gerd K