Chp 5 Challenge Solution

Thursday, October 06, 2005

In continuation of the sharing of my solutions for challenges shown in Cocoa Programming for Mac OS X, here's chapter 5. The challenge is to create an application to demonstrate the use of a delegate for a NSWindow that keeps the height at twice the desired width.

Start out by creating a new Cocoa Application project.

Once ready open the MainMenu.nib file from the project in Interface Builder. In the classes tab of the MainMenu.nib palette, create a subclass of an NSObject and name it "WindowResizer". Now create an instance of the WindowResizer class. Once that's done, switch to the Instances tab, and control drag from the Window to the WindowResizer instance, and connect the WindowResizer object as the delegate of the window.

Now we need to create the files for the WindowResizer class. To do so, go back to the classes tab and select the WindowResizer class we've added. Now create the .m and .h files adding them to your project. (Classes menu option)

Save and close the MainMenu.nib file.

Now we need to go to XCode and edit the WindowResizer.m file. Add the following method to the implementation block.

- (NSSize)windowWillResize:(NSWindow*)sender
toSize:(NSSize)frameSize {
return NSMakeSize(frameSize.width, frameSize.width * 2);

Compile and run the application and you should see the window resize with the contraint we added. One thing you'll probably notice is that the first time we resize the window shifts abruptly, because the starting dimensions don't jive with the constraint so the first time the delegate message is sent, the window will shift quite a bit. To lessen the shock you could go back to the nib file and have the window start with a width of 250 and a height of 500, or some other dimension that match the constraint.

Happy Cocoa Travels!

This page is powered by Blogger. Isn't yours?