views:

429

answers:

2

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.

A: 

Did you try overriding the initWithCoder method, just in case it is loaded from a nib somehow?

willcodejavaforfood
+4  A: 

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 was as 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:

- (void)myCheckboxToggle:(id)sender
{
    myCheckboxButton.selected = !myCheckboxButton.selected; // toggle the selected property, just a simple BOOL

    if (myCheckboxButton.selected)
    {
        myCheckboxButton.image = checkedImaged;
    }
    else
    {
        myCheckboxButton.image = nonCheckedImage;
    }
}
Jasarien