I have a problem using NSSize
I'm doing the challenge exercises in Aaron Hillegass' book Cocoa Programming for Mac. What I'm trying to do is have a window resize to twice the height of the width. Here is my code so far.
#i开发者_开发技巧mport "AppController.h"
@implementation AppController
-(id) init
{
[super init];
NSLog(@"init");
[window setDelegate:self];
return self;
}
-(NSSize) windowWillResize:(NSWindow*) sender
toSize:(NSSize)frameSize
{
int x;
NSSize mySize;
mySize.width = x;
mySize.height = 2*x;
NSLog(@"mySize is %f wide and %f tall",mySize.width,mySize.height);
return mySize;
}
This does not work as intended I'm sure I'm not using the NSSize type correctly. I don't know a lot of C so using the struct is where I think I'm making my mistake.
ADDENDUM: I changed the above code to the following.I know that I'm being passed an NSSize so there is no reason to create another one (i.e. mySize).However, I don't understand why this works. Can someone explain.
#import "AppController.h"
@implementation AppController
-(id) init
{
[super init];
NSLog(@"init");
[window setDelegate:self];
return self;
}
-(NSSize) windowWillResize:(NSWindow*) sender
toSize:(NSSize)frameSize
{
//float x = 100;
//NSSize mySize;
//mySize.width = x;
//mySize.height = x * 2;
//NSLog(@"mySize is %f wide and %f tall",mySize.width,mySize.height);
NSLog(@"mySize is %f wide and %f tall",frameSize.width,frameSize.height);
return NSMakeSize(frameSize.width, frameSize.width * 2);
}
@end
Let's think about what you want mySize to be.
- You want its width to be the same as
frameSize.width
- You want its height to be
frameSize.width * 2
.
Now let's look at what you do with x
:
- You set
mySize.width
to be equal to it - You set
mySize.height
to bex * 2
From this we can conclude:
You want to set x
to frameSize.width
.
Alternatively, the entire method could just be return NSMakeSize(frameSize.width, frameSize.width * 2)
.
You should assign an initial value to x
:
int x = 100;
Otherwise, outcome is undefined.
精彩评论