Changing the visibility of a Window element from a subclass of WebView

I am trying to make a very simple application. It is just a super simple 3 page web browser. 3 web views, 2 hidden at all times.

I have subclassed WebView to be able to capture keypress events when focusing. This part works.

Now I need to call back home and change the visibility of other WebViews when I click CMD + 1, CMD + 2, CMD + 3 (1 will show the first webview, hide 2 others, etc.).

I tried to think about how to use delegates to achieve my goal, but my lack of knowledge prevents me from completing this simple application.

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 this.

Can anyone point me in the right direction?

TL; DR; When WebView catches CMD + 1, for example, I want to be able to call a method on other WebViews so that they are hidden.

Thank you and have a nice day!

+6
source share
2 answers

Using notifications: let's say where you catch the key stroke, you have an NSString object containing some identifier to identify the desired WebView (for example, @"1" or @"2" , etc.), and each web view has viewID property. Therefore, when you get the key touch, you should add:

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

Somewhere where your webview is initialized (e.g. -awakeFromNib or -init), you add this code:

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

Then we 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 } } 

The final part: you need to remove the observer when the web view disappears, so add this to your -dealloc method:

 [[NSNotificationCenter defaultCenter]removeObserver:self]; 

That should do it.

+1
source

If I understand your question correctly, I think you can use NSUserDefaults to save small states in the application, here is an Example

Hope I helped, Best of luck :)

0
source

Source: https://habr.com/ru/post/945962/


All Articles