I have an iPhone App with a view which contains 2 buttons. I created these buttons in the Interface Builder.
Now I want to add a new button to the view programmatically:
- (void) addButton {
//allocate the view
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
//set the view's background color
self.view.backgroundColor = [UIColor whiteColor];
//create the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
//button.frame = CGRectMake(100, 10, 50,50);
button.frame = CGRectMake(100, 100, 10,10);
//set the button's title
[button setTitle:@"Click Me!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(myButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
//add the button to the view
[self.view addSubview:button];
}
Done, and it works, however the other 2 buttons which were added in Interface Builder have disappeared. The new button is quite small and only covers a small bit of the view.
Could anyone tell me where my buttons are going to?
Why are you allocating another view? It will replace the old one and everything it contains.
Just create the button.