views:

384

answers:

4

Just created a new project in Xcode (View based), and tried creating a button like this programmatically, but it doesn't show. Why not?

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after app launch    
    [window addSubview:viewController.view];

    CGRect rect = CGRectMake(0, 20,100,20);
    UIButton *button = [[UIButton alloc] initWithFrame:rect];

    [viewController.view addSubview:button];

    [window makeKeyAndVisible];
}
A: 

Don't do that. Use the Interface Builder.

mcandre
The down-ratings are a bit harsh, but I do agree that it's not a great answer. I find the Interface Builder much too clumsy for significant customization. It's more trouble than it's worth.
Amagrammer
A: 

Are you sure its not showing? it could just be transparent and you cant see it, try settings the buttons background color to something...

Daniel
I tried changing the backgroundcolor of the button with setBackgroundColor, but that didn't make any difference.
quano
try adding the button after you make window visible, what happens then?
Daniel
No difference.
quano
I tried adding it to the window instead, and then you can see it. It's just a rectangle though, and not interactable.
quano
is your view invisible? its not interactable because the view is on top of it....
Daniel
I don't add the view at all, I add the button directly to the window. So it's just the button and the window.
quano
+1  A: 

Better that you don't use the application delegate to set up your view, just load your first root view. So change the appDelegate's applicationDidFinishLaunching: back to

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after app launch    
    [window addSubview:viewController.view];

    [window makeKeyAndVisible];
}

And go into your view that it calls and punch in this code, that'll create your UIButton for you. I've also added the change of the background color to make sure you're loading this view.

- (void)loadView {
    self.view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    self.view.backgroundColor = [UIColor redColor];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 100, 20)];
    [button setTitle:@"UIButton!" forState:UIControlStateNormal];
    [button setReversesTitleShadowWhenHighlighted:YES];
    [button setShowsTouchWhenHighlighted:YES];

    [self.view addSubview:button];
    [button release];
}

Usually I'd prefer to programatically build my views since I can override drawRect: which you can't do inside InterfaceBuilder afaik.

David Wong
+1  A: 

Try creating your button with [UIButton buttonWithType: UIButtonTypeCustom] or [UIButton buttonWithType: UIButtonTypeRoundedRect]

I find those work a lot better. They are certainly much more self-documenting.

Amagrammer