How can I create basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, a three UIButton will create dynamically and set its layout or properties.
To add a button programatically to your controller's view, use the following:
-(void)viewDidLoad
{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn setTitle:@"Hello, world!" forState:UIControlStateNormal];
[self.view addSubview:btn];
}
To add three of these, rinse and repeat.
Here's one:
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
are you trying to create three dynamic instances of a button? if not, then the answer is mahboudz above.
otherwise, you can just put the creator instance within a loop and dynamically add names from an array if you so wish.
- (void)viewDidLoad {
[super viewDidLoad];
[self addMyButton]; // Call add button method on view load
}
- (void)addMyButton{ // Method for creating button, with background image and other properties
UIButton *playButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
playButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
[playButton setTitle:@"Play" forState:UIControlStateNormal];
playButton.backgroundColor = [UIColor clearColor];
[playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:@"blueButton.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
}
All well and good my friends, except none of the answers address 1 key issue - what if you want to set a background color on the button? Not so straight forward!
Changing this line:
playButton.backgroundColor = [UIColor clearColor];
...to this:
playButton.backgroundColor = [UIColor redColor];
Well, some interesting results. Apparently this only sets the background for the frame that the button is contained within. So you'll see that for a rounded rectangle button would display the colors ONLY in the corners! Why i do not know.
I've checked the docs, nothing. If anybody could shed some light on what should be a trivial issue it would be much appreciated. Thanks