iOS 实现多个按钮,点选一个其它都取消选中状态的最佳方法

本文介绍了一种在iOS应用中实现按钮唯一选中状态的方法。通过定义中间变量记录当前选中状态的按钮,并在用户点击其他按钮时取消当前选中按钮的状态,从而确保任何时候只有一个按钮处于选中状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先说一下原理,就是利用中间变量来记录某个选中状态的按钮,加一个判断,如果用户下一次点击的不是这个按钮那么用中间变量把这个按钮的选中状态取消掉,再把新的按钮赋值给中间变量,这能保证选中状态的惟一性。这里是OC 应用在iOS 项目中的,下面来看具体实现。

首先我们先定义一个中间变量

 

@property (strong,nonatomic)UIButton * tmpBtn;

然后在ViewDidLoad方法里,创建四个按钮,设置它们属性,以及点击方法,在此外设置中间变量tmpBtn = nil;

 

 

—(void)viewDidLoad{
     NSArray * array = [NSArray arrayWithObjects:@"默认",@"销量",@"价格",@"时间", nil];
         for (int i = 0; i<4; i ++) {
            UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(80*i, 0, 80, 40)];
            [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
            [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [button.layer setBorderWidth:0.3];
            button.userInteractionEnabled = YES;
            [button addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
            [button setBackgroundColor:[UIColor whiteColor]];
            [button setTag:i];
            [self.view addSubview:button];


}



 

下面来看buttonselected:里面的实现过程

 

 

-(void)buttonSelected:(UIButton*)sender{
    if (_tmpBtn == nil){
        sender.selected = YES;
        _tmpBtn = sender;
    }
    else if (_tmpBtn !=nil && _tmpBtn == sender){
        sender.selected = YES;
    
    }
    else if (_tmpBtn!= btn && _tmpBtn!=nil){
        _tmpBtn.selected = NO;
        sender.selected = YES;
        _tmpBtn = btn;
    }


}

转载于:https://www.cnblogs.com/luqinbin/p/4874138.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值