(BOOL)windowShouldClose:(id)sender doesn't work in view that i set as contentview of mainmenu's window

StackOverflow https://stackoverflow.com/questions/10083656

  •  30-05-2021
  •  | 
  •  

Question

I set a NSViewController's view as contentview of mainmenu's window,now how should i use - (BOOL)windowShouldClose:(id)sender ?

i use <NSWindowDelegate> in @interface and put - (BOOL)windowShouldClose:(id)sender on .m but doesn't work

Was it helpful?

Solution

-(BOOL)windowShouldClose:(id)sender only gets sent to the delegate of the window that will be sending the message. (if you're not crystal clear on what delegates are, they're kind of like the army commander that everybody reports to)

Here, in order to be able to use -windowShouldClose: in your NSViewController, you need to set the NSViewController as the window's delegate. There's two steps to this:

  1. Make it possible for the 'NSViewController' to be the window delegate. Usually the window's delegate is the NSWindowController (it's named that for a reason), but if you want to make 'NSViewController' the delegate you need to use the <NSWindowDelegate> protocol, which you've already done.

  2. Actually set the view controller as the delegate. As Ken Thomases noted in his comment, you can do this in Interface Builder by dragging the window's delegate outlet and connecting it to your NSViewController. Or you could do it programmatically: [self.view.window setDelegate:self] as you mentioned should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top