Challenge: Make a Delegate


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

@interface JibberWindowDelegate : NSObject <NSWindowDelegate>

@end


#22

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?


#23

You would simply equip each window with a customized delegate.


#24

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:

//AppDelegate.h

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>

@end

//AppDelegate.m

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

@end

@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
}


@end

//WindowDelegate.h

#ifndef WindowDelegate_h
#define WindowDelegate_h


#endif /* WindowDelegate_h */

#import <Cocoa/Cocoa.h>

@interface WindowDelegate : NSObject <NSWindowDelegate>

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

@end

//WindowDelegate.m

#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;
}

@end

Thanks Ibex10, you truly are my only hope.


#25

Yes.

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.


#26

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!!!