Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone toggle button implementation

Tags:

iphone

I would like to create a toggle button in my iPhone application. However, I don't know exactly what would be the best approach for this.

I am considering two options.

I could subclass an UIButton. That way I do not have to implement touch handling. I could just create a method that returns a boolean indicating whether the button is in on or off state.

I could also start with an UIView subclass and create it from scratch. I suppose it would be easier to do things like a transition animation, but I would have to create my own touch handling.

What do you think is the best one? Or would you know a better way? (Maybe there is an open-source/free view available on the web?)

EDIT: I don't want to use the UISwitch because I want my toggle button to look like that. I want it to be a big rectangular button and make the background change to indicate the state.

Thanks!

like image 644
Pieter Jongsma Avatar asked Aug 21 '09 21:08

Pieter Jongsma


2 Answers

-(IBAction)toggle{
    if (button.selected == NO) {
        button.selected = YES;

    }
    else {
        button.selected = NO;
    }
}

or

-(IBAction)toggle:(UIButton*)sender
{
sender.selected = !sender.selected;
}

simple dude

like image 87
Mashhadi Avatar answered Sep 22 '22 22:09

Mashhadi


You can use UIButton and set its enabled property.

In Interface Builder, you can set separate images for the enabled and disabled states, and the IBAction change the property.

like image 39
pgb Avatar answered Sep 23 '22 22:09

pgb