iPhone UIButton with UISwitch functionality

IphoneUibuttonUiswitch

Iphone Problem Overview


Is there either a way to implement UISwitch with custom graphics for the switch-states? Or as an alternative the other way round, an UIButton with UISwitch functionality?

Iphone Solutions


Solution 1 - Iphone

UIButton already supports a "switch" functionality.

Just set a different image in Interface Builder for the "Selected State Configuration", and use the selected property of UIButton to toggle its state.

Solution 2 - Iphone

set the image to show on selected state:

[button setImage:[UIImage imageNamed:@"btn_graphics"] forState:UIControlStateSelected];

and then on touch up inside selector, set:

button.selected = YES;

if you want this to cancel another button's selection, set:

otherButton.selected = NO;

Solution 3 - Iphone

To build on what PGB and nurne said above, after you set your states and attach a selector (event method) you would want to put this code in that selector.

- (IBAction)cost:(id)sender 
{
    //Toggle current state and save
    self.buttonTest.selected = !self.buttonTest.selected;

    /**
     The rest of your method goes here.
     */
}

Solution 4 - Iphone

For programmatically inclined:

-(void) addToggleButton {
    CGRect aframe = CGRectMake(0,0,100,100);
    
    UIImage *selectedImage = [UIImage imageNamed:@"selected"];
    UIImage *unselectedImage = [UIImage imageNamed:@"unselected"];
    
    self.toggleUIButton = [[UIButton alloc] initWithFrame:aframe];
    [self.toggleUIButton setImage:unselectedImage forState:UIControlStateNormal];
    [self.toggleUIButton setImage:selectedImage forState:UIControlStateSelected];
    [self.toggleUIButton addTarget:self 
                            action:@selector(clickToggle:) 
                  forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.toggleUIButton];
}

-(void) clickToggle:(id) sender {
    BOOL isSelected = [(UIButton *)sender isSelected];
    [(UIButton *) sender setSelected:!isSelected];
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionscudView Question on Stackoverflow
Solution 1 - IphonepgbView Answer on Stackoverflow
Solution 2 - IphonenurnachmanView Answer on Stackoverflow
Solution 3 - IphoneShaoloView Answer on Stackoverflow
Solution 4 - IphoneThunder RabbitView Answer on Stackoverflow