If I have two images for a UIButton (box with checkmark, box without checkmark), do I want to subclass UIButton? If so, how do I know when the button is pressed to set the two images for the on/off (or checked/not checked) state?
If I’m not supposed to subclass UIButton, then do I do something like this every time I want to use a checkmark button in a class?
.h
@property (nonatomic, assign) BOOL isPressed;
.m
- (IBAction)buttonPressed:(id)sender {
isPressed = !isPressed;
if (isPressed) {
UIImage *checked = [UIImage imageNamed:@"checked.png"];
[button setImage:checked forState:UIControlStateNormal];
}
else {
UIImage *unchecked = [UIImage imageNamed:@"unchecked.png"];
[button setImage:unchecked.png forState:UIControlStateNormal];
}
}
UIButton has several possible states – normal, highlighted and selected and you can assign separate images for each state. Then in action method just toggle selected state for the button and it will handle image change for you: