iDevGames Forums
How to instantiate a control in code instead of using Interface Builder ? - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: iPhone, iPad & iPod Game Development (/forum-11.html)
+--- Thread: How to instantiate a control in code instead of using Interface Builder ? (/thread-631.html)



How to instantiate a control in code instead of using Interface Builder ? - Bracer - Nov 2, 2009 11:01 PM

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();
}



How to instantiate a control in code instead of using Interface Builder ? - SethWillits - Nov 3, 2009 01:33 PM

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.


How to instantiate a control in code instead of using Interface Builder ? - ThemsAllTook - Nov 3, 2009 01:41 PM

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.