Skip navigation.
 
mlRe: Adding GUI components dynamically
FROM : Jens Alfke
DATE : Mon Mar 03 22:53:36 2008

On 1 Mar '08, at 2:07 PM, Dimitri Bouniol wrote:

> Easy. Create an instance of a NSButton:
> NSButton *myButton = [[NSButton alloc] initWithFrame:nsRectOfButton];
>
> Then add it to your view:
> [view addSubview:myButton];


I would recommend against doing this, for several reasons:

1. Last time I tried, it was very tricky to set the button up 
correctly. There are many attributes you'll probably want to change, 
and they need to be changed in a particular order (which you have to 
find by trial and error.)
2. Doing this makes your app very difficult to localize, because it 
requires editing the source code. Localizers are used to modifying 
Interface Builder documents and strings files; they're usually not 
programmers.
3. Your app can't switch languages on demand (i.e. support multiple 
languages with a single binary) without extra work.
4. It's not The Way Things Are Done in Cocoa, so it'll confuse/annoy 
any other programmer who tries to read your code.

The better way to do this is to make the button in Interface Builder. 
Add a "custom view" object to your nib (not inside a window, just drag 
in into the nib itself), then add the button to that view, and add an 
outlet from your controller object that points to the button.
Then at runtime you can remove the button from its superview and add 
it somewhere in your window.

In most situations where you need to create multiple copies of a 
button (like a radio button group)  you should use an NSMatrix. Just 
set its number of rows at runtime, and it'll duplicate its cell that 
many times.

—Jens

Related mailsAuthorDate
mlAdding GUI components dynamically Thiago Rossi Mar 1, 21:49
mlRe: Adding GUI components dynamically Dimitri Bouniol Mar 1, 23:07
mlRe: Adding GUI components dynamically Thiago Rossi Mar 2, 04:18
mlRe: Adding GUI components dynamically Jens Alfke Mar 3, 22:53