/ Published in: Objective C
Create a UIButton programatically
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Create a Button UIButton *myButton = [[UIButton buttonWithType: UIButtonTypeRoundedRect]; // To be notified when a button changes state, add a target and action: [myButton addTarget:self action: @selector(buttonClick:) forControlEvents:UIControlEvent TouchUpInside]; // To create a button with a image -(void)buttonDown:(id)sender { NSLog(@"Button pushed down"); } -(void)buttonRelease:(id)sender { NSLog(@"Button released"); } -(void)checkboxClick:(UIButton *)btn { btn.selected = !btn.selected; } - (void)viewDidLoad { [super viewDidLoad]; //rounded-rect button UIButton *roundedRectButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; CGRect buttonRect = CGRectMake(100,50,100,35); [roundedRectButton setFrame:buttonRect]; [roundedRectButton setTitle:@"Normal" forState:UIControlStateNormal]; [roundedRectButton setTitle:@"Highlighted" forState:UIControlStateHighlighted]; roundedRectButton.showsTouchWhenHighlighted = YES; [roundedRectButton addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown]; [roundedRectButton addTarget:self action:@selector(buttonRelease:) forControlEvents:UIControlEventTouchUpInside]; //checkbox control UIButton *checkbox = [UIButton buttonWithType:UIButtonTypeCustom]; CGRect checkboxRect = CGRectMake(135,150,36,36); [checkbox setFrame:checkboxRect]; [checkbox setImage:[UIImage imageNamed:@"checkbox_off.png"] forState:UIControlStateNormal]; [checkbox setImage:[UIImage imageNamed:@"checkbox_on.png"] forState:UIControlStateSelected]; [checkbox addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside]; //custom circular button UIButton *circularButton = [UIButton buttonWithType:UIButtonTypeCustom]; CGRect circularRect = CGRectMake(80,220,165,164); [circularButton setFrame:circularRect]; UIImage *buttonImage = [UIImage imageNamed:@"circular_button.png"]; [circularButton setImage:buttonImage forState:UIControlStateNormal]; [circularButton addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchUpInside]; //add all the buttons to the main view [self.view addSubview:roundedRectButton]; [self.view addSubview:checkbox]; [self.view addSubview:circularButton]; }