具有UISwitchfunction的iPhone UIButton

有没有一种方法来实现开关状态自定义graphics的UISwitch? 或者换个angular度来看,UIButton具有UISwitchfunction?

UIButton已经支持“开关”function。

只需在Interface Builder中为“Selected State Configuration”设置一个不同的图像,并使用UIButtonselected属性来切换其状态。

设置图像显示在选定的状态:

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

然后触摸里面的select器,设置:

 button.selected = YES; 

如果您想要取消另一个button的select,请设置:

 otherButton.selected = NO; 

要build立PGB和nurne上面所说的,在设置你的状态并附加一个select器(事件方法)之后,你会想把这个代码放在那个select器中。

 - (IBAction)cost:(id)sender { //Toggle current state and save self.buttonTest.selected = !self.buttonTest.selected; /** The rest of your method goes here. */ } 

对于编程倾向:

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