How do I create a basic UIButton programmatically?

domlao picture domlao · Sep 4, 2009 · Viewed 546.7k times · Source

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButtons will be created dynamically and its layout or properties are set.

Answer

mahboudz picture mahboudz · Sep 4, 2009

Here's one:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];