Challenge: Make a Delegate

#import <AppKit/AppKit.h>
// or #import <Cocoa/Cocoa.h>

@interface JibberWindowDelegate : NSObject <NSWindowDelegate>



Ah, okay. When I create new .h and .m files, the #import cocoa/cocoa.h (sorry, again the lesser than / greater than signs cause the text to disappear) is not automatically placed in the header file. That does solve my build issues. However… it still doesn’t work. I run… and I can resize the window to any shape… it is in no way constrained to a length = width*2 aspect ratio. I feel like the crucial step I’m missing is to create a delegate outlet for *window, and assign WindowDelegate to be said delegate. Something like [_window setDelegate: WindowDelegate];. That would make sense, now there’s a connection. Otherwise, what if you had four windows, but only wanted WindowDelegate to constrain the dimensions of one of them. How would you indicate that?


You would simply equip each window with a customized delegate.


Okay, I feel like we are close. This builds, but when I run it the window is not constrained in any way. I feel like I am missing some way of telling this window object (called *window) that the WindowDelegate is its delegate. Right now, WindowDelegate could be any windows delegate, yes? Here is my code:


#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>



#import "AppDelegate.h"

@interface AppDelegate ()

@property (weak) IBOutlet NSWindow *window;
//worth noting, I didn't create the outlet above
//it was automatically created by xcode.


@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application



#ifndef WindowDelegate_h
#define WindowDelegate_h

#endif /* WindowDelegate_h */

#import <Cocoa/Cocoa.h>

@interface WindowDelegate : NSObject <NSWindowDelegate>

- (NSSize)windowWillResize:(NSWindow *)sender toSize: (NSSize)frameSize;



#import <Foundation/Foundation.h>
#import "WindowDelegate.h"

@implementation WindowDelegate

- (NSSize)windowWillResize:(NSWindow *)sender toSize: (NSSize)frameSize
    NSSize newSize = frameSize;
    newSize.height = newSize.width * 2;
    return newSize;


Thanks Ibex10, you truly are my only hope.



If you haven’t already done this, try this:

In IB, that is, in Interface Builder:

  1. Create an object and set its class type to that of your window delegate class.

  2. Bind that object to window’s delegate outlet.

Here is what it looks like in thousands of pixels.


Success! I knew it had nothing to do with code… but the strange and weird ways of control-dragging and connecting things. That is a dark and murky world… sigh. Thank you so much!!!