UIButton

A UIButton represents a rectangular button that the user can tap. When a user taps the button, a method that you write is executed.

Example
UIView *myView =
   [ [UIView alloc]
   initWithFrame:[[UIScreen mainScreen]
   applicationFrame] ];

self.view = myView;
[myView release];

Declaring a button reference variable
UIButton *button;

Creating a button object and assigning it to a variable
button = [UIButton
   buttonWithType:
   UIButtonTypeRoundedRect];

Setting the x,y,width,height of a button
[button setFrame:
   CGRectMake(0,381,60,30)];

Setting the text (title) on a button
[button setTitle:
   @"Larger" forState:UIControlStateNormal];

Setting a background color on a button
[button setBackgroundColor:
   [UIColor redColor]];

Setting the target method to call for a button
[button addTarget:self
   action:@selector(buttonTouched:)
   forControlEvents:
   UIControlEventTouchUpInside];

Putting the button on the screen (on the UIView)
[myView addSubview:button];

Writing the responder method for the button
-(void) buttonTouched:(id) sender
{
  // do whatever
}



// Also see UIBarButtonItem
// for navigationItem
self.navigationItem.leftBarButtonItem =
   [[UIBarButtonItem alloc]
   initWithTitle:@"Back"
   style:UIBarButtonItemStylePlain
   target:self
   action:@selector(switch:)];

self.navigationItem.rightBarButtonItem = nil;


Setting the image on a button
Use UIButtonTypeCustom for pictures and the method
setImage:
NSString *path = @"myimage.png";
UIImage *theImage =
  [UIImage imageNamed:path];

[button setImage:theImage];

or

[button setImage:[UIImage imageNamed:@"myimage.png"]];


Creating a UIButton manually
UIButton *button =
[UIButton buttonWithType:UIButtonTypeRoundedRect];

Setting a background image on a button
[button setBackgroundImage:anImage forState:UIControlStateNormal];

Setting the text (title) on a button
[button setTitle:@"someText" forState:UIControlStateNormal];

Setting the font, text, and text color on a button
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle: @"My Button" forState: UIControlStateNormal];
[button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];


Getting the text on a button
NSString *myTextOnButton = [button currentTitle];
or
NSString *buttonTitle = button.currentTitle;


Getting the image on a button
UIIMage *myImageOnButton = [button currentImage];
or
UIImage *buttonImage = button.currentImage;


Hiding a button
[button setHidden:YES];


Unhiding a button
[button setHidden:NO];


Getting the x and y coordinates of a button
float x = button.frame.origin.x;
float y = button.frame.origin.y;


Getting the width and height of a button
float width = button.frame.size.width;
float height = button.frame.size.height;


Setting the x,y,width,height of a button
[button setFrame:
   CGRectMake(x,y,width,height)];