RSS-feed

Sun, 02 Sep 2007

Cocoa: delegating


I am reading this book since I am in the process of writing a macosx cocoa application. The book has some "Challenges" at the end of every chapter and also a wiki where everybody can ask or post stuff for every part in the book.

I have been trying to implement all the challenges, and I noticed that people had some issues implementing the challenge in chapter 5, I had them myself also. It's the one about helper objects and delegation.

Basically we have to implement an application with a main window. When the window gets resized, the height has to be twice the width. This is my solution:

  1. Create a basic main class were we will put our code. Instanciate the class (From interface builder).
  2. In your new class, implement the this delegate method
                  - (NSSize) windowWillResize:(NSWindow *) sender
                                       toSize:(NSSize)frameSize
                     {
                        NSLog(@"W wants to get resized to: width=%f, height=%f", frameSize.width, frameSize.height);
                        frameSize.width = frameSize.height/2;                    
                        NSLog(@"Windows being resized to: width=%f, height=%f", frameSize.width, frameSize.height);
                        return frameSize;
                     }
                
    NOTE: you have to return an NSSize object. Read the documentation for more info.
  3. Use the interface builder to delegate from the main window to your new class. This is the key. You have to tell the main window object that your main class is implementing some of its delegate methods so it can trigger your method.

And that's it.

posted at: 21:57 | path: /cocoa | permanent link to this entry