是否有一种方法可以为开关状态实现带有自定义图形的UISwitch? 或者作为另一种选择,UIButton具有UISwitch功能?
答案 0 :(得分:101)
UIButton
已经支持“切换”功能。
只需在Interface Builder中为“选定状态配置”设置不同的图像,并使用selected
的{{1}}属性切换其状态。
答案 1 :(得分:12)
将图像设置为在选定状态下显示:
[button setImage:[UIImage imageNamed:@"btn_graphics"] forState:UIControlStateSelected];
然后在内部选择器上触摸,设置:
button.selected = YES;
如果您想要取消其他按钮的选择,请设置:
otherButton.selected = NO;
答案 2 :(得分:7)
基于PGB和nurne上面所说的内容,在设置状态并附加选择器(事件方法)后,您可能希望将此代码放在该选择器中。
- (IBAction)cost:(id)sender
{
//Toggle current state and save
self.buttonTest.selected = !self.buttonTest.selected;
/**
The rest of your method goes here.
*/
}
答案 3 :(得分:3)
以编程方式倾斜:
-(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];
}