zoukankan      html  css  js  c++  java
  • iOS 实现多个按钮,点选一个其它都取消选中状态的最佳方法

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

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

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

     @property (strong,nonatomic)UIButton * MiddleBtn;

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

    —(void)viewDidLoad{
        MiddleBtn = nil;
    // treating unicode character as whitespace 如果出现这行警告 可能是由于粘贴网页上的代码的时候两行之间的回车引起的,两行之间重新输入回车就行...。。。删掉重新写一遍就ok了 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 (_MiddleBtn == nil){
            sender.selected = YES;
            _MiddleBtn = sender;
        }
        else if (_MiddleBtn !=nil && _MiddleBtn == sender){
            sender.selected = YES;
        
        }
        else if (_MiddleBtn!= sender && _MiddleBtn!=nil){
            _MiddleBtn.selected = NO;
            sender.selected = YES;
            _MiddleBtn = sender;
        }
    }
  • 相关阅读:
    matplotlib基础汇总_03
    matplotlib基础汇总_02
    matplotlib基础汇总_01
    水果系统(面向过程,面向对象)
    给定几位数,查看数根(使用函数实现)
    定义函数,给定一个列表作为函数参数,将列表中的非数字字符去除
    学生管理系统-明日学院的
    四平方和
    四位玫瑰数
    学生成绩表数据包括:学号,姓名,高数,英语和计算机三门课成绩,计算每个学生总分,每课程平均分,最高分和最低分
  • 原文地址:https://www.cnblogs.com/wangxiaorui/p/5497349.html
Copyright © 2011-2022 走看看