状态切换按钮,功能类似UISwitch
创建按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];button.frame = CGRectMake(10.0, 10.0, 100.0, 40.0);[button setTitle:@"Normal" forState:UIControlStateNormal];UIImage *image = [UIImage imageNamed:@"normal.png"];UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];[button setBackgroundImage:newImage forState:UIControlStateNormal];button.adjustsImageWhenHighlighted = NO;[button addTarget:self action:@selector(buttonSwitch:) forControlEvents:UIControlEventTouchDown];[self.view addSubview:button];
事件处理
-(void)buttonSwitch:(id)sender{static BOOL isHighlighted = NO;UIButton *button = (UIButton*)sender;UIImage *image = nil;NSString *title = nil;if (isHighlighted){title = @"Normal";image = [UIImage imageNamed:@"normal.png"];}else{title = @"Hightlight";image = [UIImage imageNamed:@"highlight.png"];}[button setTitle:title forState:UIControlStateNormal];UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];[button setBackgroundImage:newImage forState:UIControlStateNormal];isHighlighted = !isHighlighted;}?