Next: 3.4 Source Code Up: 3 Adding a Button Previous: 3.2 Creating a Button

3.3 Putting the button in the window

We now need to modify our code to create the window so that it creates a window exactly of the right size to contain our button. First, we need to get the size of the button:
NSSize buttonSize;

buttonSize = [myButton frame].size;
frame is a method inherited by NSView which returns the rectangle enclosing the button (or, more generally, the rectangle enclosing/represented by an NSView). The origin of this rectangle is meaningless at this point; it is the size (which was set by sizeToFit) what we want.

Then, we choose for the window a content rect with the size of the button, and with an origin of our choice; (100, 100) in this example:

NSRect rect;

rect = NSMakeRect (100, 100, 
                   buttonSize.width, 
                   buttonSize.height);
At this point, we just create the window as before, but using this rectangle (full code below). The last thing to do is then replacing the default window content view with our button:
[myWindow setContentView: myButton];



2008-01-16