Question

I want to programatically add several NSTextFields to a window when it loads. I call the below method for each one in the init such as:

- (id)initWithWindow:(NSWindow *)window{
    [self addTextField:firstTextField toWindow:window at:20];
}

-(void)addTextField:(NSTextField*)theTextField toWindow:(NSWindow*)theWindow at:(CGFloat)y{

    theTextField = [[NSTextField alloc] initWithFrame:NSMakeRect(10, y, 200, 20)];
    [theTextField setBezeled:NO];
    [theTextField setDrawsBackground:NO];
    [theTextField setEditable:NO];
    [theTextField setSelectable:YES];

    [[theWindow contentView] addSubview:theTextField];
}

I don't get any errors, not even when I call the setStringValue for one of the NSTextFields. However, they are not visible in the window. Have I missed something simple, or am I trying something that is not allowed?

Thanks

Was it helpful?

Solution

Try like this:-

- (void)windowDidLoad
{
  NSRect frameRect = NSMakeRect(10, 20, 200, 20);
  NSTextField *theTextField = [[NSTextField alloc] initWithFrame:frameRect];
  [theTextField setBezeled:YES];
  [theTextField setDrawsBackground:NO];
  [theTextField setEditable:NO];
  [theTextField setSelectable:YES];
  [vw addSubview:theTextField]; 
  [[[self window]contentView]addSubview:vw];
  [super windowDidLoad];

  // Implement this method to handle any initialization after your window controller's   window has been loaded from its nib file.
}

OTHER TIPS

If you load your window from xib you shouldn't override -initWithWindow:, use -windowDidLoad instead and add your textfields in this method. But if you create your window programmatically your -initWithWindow: must look like this:

-(id)initWithWindow:(NSWindow*)window {
    self = [super initWithWindow:window];
    if(self) {
        [self addTextField:firstTextField toWindow:self.window at:20];
    }
    return self;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top