How can get a reference to an NSWindow created in

2019-07-28 03:26发布

问题:

I use a xib file to show an NSWindow named mainWindow - now I want to get a reference to mainWindow via code (e.g. NSWindow *mainWindow). I can't find anything in the documentation, any pointers?

回答1:

The xib file will have placeholder objects in it for the app delegate and / or the file's owner.

On the assumption that it has the app delegate in it, you can get a reference to the window or any object in the xib by

  1. Declare a property in the app delegate of the right type and with IBOutlet as part of its type:

    @property (weak) IBOutlet NSWindow* theWindow;
    
  2. Locate the app delegate object in the xib. Click and drag it while the control key is pressed. You should get a line between the mouse pointer and the object.

  3. Drag on to the window and release the mouse button.
  4. You should see a list of the outlets in the app delegate. Select theWindow and your done.