Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to make a UIButton checkbox?

I am trying to make a standard check box for my iPhone app from a UIButton with a title and image. The button image changes between an "unchecked" image and a "checked" image.

At first I tried subclassing UIButton but UIButton has no -init*** method to use in my -init method.

What is the best way to do this?

Thanks in advance.

like image 394
cduck Avatar asked Feb 09 '10 07:02

cduck


People also ask

How do I add text to UIButton?

Programmatically. To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .


1 Answers

You shouldn't need to subclass the UIButton class. By design, Objective-C favors composition over inheritance.

UIButton is a subclass of UIControl, which has a selected property. You can use this property to toggle the on/off behaviour of a checkbox, just the same way a UISwitch does.

You can attach an action to the button's touched up inside event, and perform the toggling in there, something like this:

// when you setup your button, set an image for the selected and normal states
[myCheckBoxButton setImage:checkedImage forState:UIControlStateSelected];
[myCheckBoxButton setImage:nonCheckedImage forState:UIControlStateNormal];

- (void)myCheckboxToggle:(id)sender
{
    myCheckboxButton.selected = !myCheckboxButton.selected; // toggle the selected property, just a simple BOOL
}
like image 101
Jasarien Avatar answered Sep 20 '22 13:09

Jasarien