首页 > 移动平台 > 详细

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

时间:2015-10-26 15:39:19      阅读:293      评论:0      收藏:0      [点我收藏+]

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

@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;
    }


}

代码直接粘贴可用。


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

原文:http://my.oschina.net/u/2450398/blog/522139

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!