I'm a beginner Cocoa programmer. I wish to position a Cocoa NSTextField (a subview of a custom view) programmatically next to a geometric diagram drawn on the custom view in a program to be developed with XCode 4.3.2 for OS X on Lion. To keep the example of my problem simple, let's say the diagram is to be a box enclosing the text field (additional to the bezel or border available with NSTextField, and further out; actually, my diagram is to be more complicated). I find that the text field and the box do not align as I expect (see example code below). Why?
I've made a simple non-Document-based project as a diagnostic example, in which I've dragged a custom view onto the application window, added the code below, and made the connection from the IBOutlet to the view:
AnAppDelegate.h:
#import <Cocoa/Cocoa.h>
@interface AnAppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSView *view;
NSRect textFieldRect;
NSTextField *textField;
NSBezierPath *box;
}
@property (assign) IBOutlet NSWindow *window;
@end
AnAppDelegate.m:
#import "AnAppDelegate.h"
@implementation AnAppDelegate
@synthesize window = _window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
textFieldRect = NSMakeRect(100, 100, 100, 20);
textField = [[NSTextField alloc] initWithFrame:textFieldRect];
NSRect frame = [textField frame];
NSLog(@"frame %f %f %f %f", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
NSRect bounds = [textField bounds];
NSLog(@"bounds %f %f %f %f", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
// Draw the text field
[textField setStringValue:@"My text field"];
[textField setBezeled:YES];
[textField setDrawsBackground:NO];
[textField setEditable:YES];
[textField setSelectable:YES];
[view addSubview:textField];
// Draw a box (rectangle) around the text field
//NSRect boxRect = [textField frame];
box = [[NSBezierPath alloc] init];
//boxRect.origin.x += 10;
//boxRect.origin.y += 10;
//boxRect.size.width += 20;
//boxRect.size.height += 20;
[box appendBezierPathWithRect:[textField frame]]; // :boxRect];
[box stroke];
}
@end
When this program is run, the box appears displaced to the left and below the text field, apparently by the height of the text field in each dimension. I'd expect it to appear 'underneath' the NSTextField subview, and to be hidden by it. (That's not sensible in a production program, of course.)
Now, to get closer to what I want, if one uncomments the commented-out lines of the source above (appending boxRect to the box path instead of the frame of the text field), then my box appears outset by 10 units from the text frame - but I expected that I should have had to add -10 units to the origin to do that, not +10 units.
What is going on?