iPhone UIButton with UISwitch functionality

天涯浪子 提交于 2019-12-17 10:22:33

问题


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?


回答1:


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.




回答2:


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;



回答3:


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.
     */
}



回答4:


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];
}


来源:https://stackoverflow.com/questions/2255166/iphone-uibutton-with-uiswitch-functionality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!