IOS UIButton实现checkbox按钮二选一(单选框,复选框)

> 实现了简单的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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值