Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a UIButton at runtime

I am trying to add a UIButton at runtime however it is not visible. What am I doing wrong?

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIButton *btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        btn.frame = CGRectMake(0, 0, 100, 25);
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitle:@"Play" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonClick:)
        forControlEvents:UIControlEventTouchUpInside];
        btn.center = self.center;
        [self addSubview:btn];
    }
    return self;
}
like image 1000
Jamey McElveen Avatar asked Nov 21 '08 04:11

Jamey McElveen


2 Answers

First, make sure the initWithFrame: method is being called. If your view is in a Nib, initWithCoder: is being called instead.

Second, is the button the only subview (from your code it looks like it is, but you never know). The button could be hidden behind another subview. Call bringSubviewToFront: if you need to.

Finally, is the view itself visible? Is it big enough to show the button? Given your example, if the view is less than 100 pixels wide, the button won't show because it will get clipped by the view's bounds.

like image 115
August Avatar answered Nov 18 '22 22:11

August


You must release btn and remove ":" in buttonClick:

UIButton *btn= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:@"Play" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn]; 
[btn release];
like image 42
NguyenHungA5 Avatar answered Nov 18 '22 23:11

NguyenHungA5