Create a UIButton programatically


/ Published in: Objective C
Save to your folder(s)

Create a UIButton programatically


Copy this code and paste it in your HTML
  1. // Create a Button
  2. UIButton *myButton = [[UIButton buttonWithType: UIButtonTypeRoundedRect];
  3.  
  4. // To be notified when a button changes state, add a target and action:
  5. [myButton addTarget:self action: @selector(buttonClick:) forControlEvents:UIControlEvent TouchUpInside];
  6.  
  7. // To create a button with a image
  8.  
  9.  
  10.  
  11.  
  12.  
  13. -(void)buttonDown:(id)sender
  14. {
  15. NSLog(@"Button pushed down");
  16. }
  17.  
  18. -(void)buttonRelease:(id)sender
  19. {
  20. NSLog(@"Button released");
  21. }
  22.  
  23. -(void)checkboxClick:(UIButton *)btn
  24. {
  25. btn.selected = !btn.selected;
  26. }
  27.  
  28. - (void)viewDidLoad {
  29.  
  30. [super viewDidLoad];
  31.  
  32. //rounded-rect button
  33. UIButton *roundedRectButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  34.  
  35. CGRect buttonRect = CGRectMake(100,50,100,35);
  36. [roundedRectButton setFrame:buttonRect];
  37.  
  38. [roundedRectButton setTitle:@"Normal" forState:UIControlStateNormal];
  39. [roundedRectButton setTitle:@"Highlighted" forState:UIControlStateHighlighted];
  40. roundedRectButton.showsTouchWhenHighlighted = YES;
  41.  
  42. [roundedRectButton addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown];
  43. [roundedRectButton addTarget:self action:@selector(buttonRelease:) forControlEvents:UIControlEventTouchUpInside];
  44.  
  45. //checkbox control
  46. UIButton *checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
  47.  
  48. CGRect checkboxRect = CGRectMake(135,150,36,36);
  49. [checkbox setFrame:checkboxRect];
  50.  
  51. [checkbox setImage:[UIImage imageNamed:@"checkbox_off.png"] forState:UIControlStateNormal];
  52. [checkbox setImage:[UIImage imageNamed:@"checkbox_on.png"] forState:UIControlStateSelected];
  53.  
  54. [checkbox addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
  55.  
  56. //custom circular button
  57. UIButton *circularButton = [UIButton buttonWithType:UIButtonTypeCustom];
  58.  
  59. CGRect circularRect = CGRectMake(80,220,165,164);
  60. [circularButton setFrame:circularRect];
  61.  
  62. UIImage *buttonImage = [UIImage imageNamed:@"circular_button.png"];
  63. [circularButton setImage:buttonImage forState:UIControlStateNormal];
  64.  
  65. [circularButton addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchUpInside];
  66.  
  67. //add all the buttons to the main view
  68. [self.view addSubview:roundedRectButton];
  69. [self.view addSubview:checkbox];
  70. [self.view addSubview:circularButton];
  71. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.