How to instantiate a control in code instead of using Interface Builder ?

Nibbie
Posts: 4
Joined: 2009.10
Post: #1
I really appreciate the combination of the interface builder and Xcode altogether.
However when I am learning QT, I realize I had been pampered by Apple's Design to a certain extend as I only need to create say a NSLabel instance and use Interface Builder to do the linking and never have to worry about instantiating the Object myself.

But I'm curious, what is the way to instantiate a new hmmm say...NSLabel in the code ?

NSLabel* label = new NSLabel();
Then what ?

What you are seeing here is how QT did it, could anyone create an equivalent in ObjC ? No fancy code please, just bare minimum.
Code:
#include <QApplication>
#include <QWidget>
#include <QLabel>

int main (int argc, char * argv [ ])
{
    QApplication app(argc, argv); //NSApplication in ObjC

    //These two lines merely created a window and set the title bar text.
    QWidget* window = new QWidget();
    window->setWindowTitle("Hello World");


    QLabel* label = new QLabel(window);//Create a label and inform the it belongs to window.
    label->setText("Hello World");
    
    window->show();

    return app.exec();
}
Quote this message in a reply
⌘-R in Chief
Posts: 1,237
Joined: 2002.05
Post: #2
First off, there's no such thing as an NSLabel. There's an NSTextField in Cocoa, and UILabel on the phone.

Second, you simply create it.
Code:
UILabel * label = [[UILabel alloc] initWithFrame:NSMakeRect(0, 0, 120, 20)];

Third, you add it to some view:
Code:
[view addSubview:label];

Fourth, you do whatever else you need to do with it.
Quote this message in a reply
Moderator
Posts: 1,560
Joined: 2003.10
Post: #3
FreakSoftware Wrote:Third, you add it to some view:

Now, if you want some view to be created programmatically, you'll probably want to create an NSWindow (see documentation) and add things to its contentView. I tried putting together a complete example earlier, but it didn't work on the first try and I didn't have time to figure out what I'd missed... If you're still having problems later, I might be able to put together a working example when I'm at home.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Question about interface builder mag709 3 3,526 Apr 23, 2012 05:40 PM
Last Post: mag709
  Changing font type in Interface Builder? Toontingy 0 3,783 Mar 29, 2009 05:42 PM
Last Post: Toontingy
  arrange - Bring to front (interface Builder) imaumac 3 7,314 Oct 6, 2008 10:44 AM
Last Post: imaumac
  Interface Builder and switching UIViews bruss14 3 4,671 Jun 20, 2008 12:52 PM
Last Post: AnotherJake