iUser
iUser

Reputation: 1075

How to create NSTextField programmatically?

I want to create NSTextField programmatically. I am new to Mac App Development.
Can anyone help me in this ?

Update :
I tried this code

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSView *myView = [[NSView alloc] init];
    NSRect frameRect = NSMakeRect(20,20,100,140);
    NSTextField *myTextField = [[NSTextField alloc] initWithFrame:frameRect];
    [myView addSubview:myTextField];
}

This does nothing. Please correct me if i'm wrong anywhere.

Thank you.

Upvotes: 3

Views: 8504

Answers (2)

Suhas
Suhas

Reputation: 1500

Creating UI elements programmatically is very simple in Cocoa.

It involves two steps:

  1. Create the view and set a frame to it.

  2. Add it as a subview to any super view.

Following snippet will you help you understand better.

NSRect frameRect = NSMakeRect(20,20,40,40); // This will change based on the size you need

NSTextField *myTextField = [[NSTextField alloc] initWithFrame:frameRect];

[myView addSubview:myTextField];

Upvotes: 4

user23743
user23743

Reputation:

It looks like you're creating an NSTextField OK, but you're not adding it to anywhere visible in the view hierarchy. Your app probably contains one or more NSWindow instances; if you want a view to appear in a particular window, you should add it as a subview of that window's content view.

Upvotes: 1

Related Questions