Thursday, May 30, 2013

UIButton setImage example in Objective C (iOS).

UIButton setImage

Sets the image to use for the specified state.

- (void)setImage:(UIImage *)image forState:(UIControlState)state

Parameters of [UIButton setImage]
image
The image to use for the specified state.
state
The state that uses the specified title. The values are described in UIControlState.

Discussion of [UIButton setImage]
In general, if a property is not specified for a state, the default is to use the UIControlStateNormal value. If the UIControlStateNormal value is not set, then the property defaults to a system value. Therefore, at a minimum, you should set the value for the normal state.

UIButton setImage example.
UIImage *listImage = [UIImage imageNamed:@"list_icon.png"];
UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];

// get the image size and apply it to the button frame
CGRect listButtonFrame = listButton.frame;
listButtonFrame.size = listImage.size;
listButton.frame = listButtonFrame;

[listButton setImage:listImage forState:UIControlStateNormal];
[listButton addTarget:self.navigationController.parentViewController action:@selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton = [[UIBarButtonItem alloc] initWithCustomView:listButton];

self.navigationItem.leftBarButtonItem = jobsButton;

Example of [UIButton setImage].
UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside];


[btnTwo setImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];

//OR setting as background image

[btnTwo setBackgroundImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];

[self.view addSubview:btnTwo];

UIButton setImage example.
[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];


-(void)buttonTouchDown:(id)sender{
    UIButton *button=(UIButton *)sender;
    if(button.selected){
        [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
    }
}

-(void)buttonTouchUp:(id)sender{
    UIButton *button=(UIButton *)sender;
    [button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
}

End of UIButton setImage example article.