> 实现了简单的CheckBox二选一功能,选择一个Button加一个View,选择另一个Button时先移除上一个View,再在原来的地方加上另一个View。
//声明button
@property (nonatomic,retain) UIButton *checkIPButton;
@property (nonatomic,retain) UIButton *checkTUTKButton;
- (void)viewDidLoad {
UIImage *checkImage = [UIImageimageNamed:@"check"];
UIImage *uncheckImage = [UIImageimageNamed:@"uncheck"];
self.checkIPButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
self.checkIPButton = 50;
self.checkIPButton.frame = CGRectMake(100,100, checkImage.size.width, checkImage.size.height);
[self.checkIPButton setBackgroundImage:uncheckImage forState:UIControlStateNormal];//正常状态图片是非选中的
[self.checkIPButton setBackgroundImage:checkImage forState:UIControlStateSelected];
self.checkIPButton.selected = YES; //初始化默认选择IP方式
[self.checkIPButton addTarget:self action:@selector(connectWayAction:)
forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:self.checkIPButton];
self.checkTUTKButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
self.checkTUTKButton.tag = 51;
self.checkTUTKButton.frame = CGRectMake(100,150, checkImage.size.width, checkImage.size.height);
[self.checkTUTKButton setBackgroundImage:uncheckImage forState:UIControlStateNormal];
[self.checkTUTKButton setBackgroundImage:checkImage forState:UIControlStateSelected];
[self.checkTUTKButton addTarget:self action:@selector(connectWayAction:)
forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:self.checkTUTKButton];
}
- (void)connectWayAction:(UIButton *)sender
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
if (sender.tag ==50) {
//移除View,添加View
[[self.view viewWithTag:61] removeFromSuperview];
[self useConnectWayForIP];
//获取另一个button
button = (UIButton *)[self.view viewWithTag:51];
}else{
[[self.view viewWithTag:60] removeFromSuperview];
[self useConnectWayForTUTK];
button = (UIButton *)[self.view viewWithTag:50];
}
//设置当前选中Button为不可交互,防止其重复添加View
sender.selected = !sender.selected;
button.selected = !button.selected;
sender.userInteractionEnabled = NO;
button.userInteractionEnabled = YES;
}
}