开发项目时,有很多场景需要用到按钮单选效果,例如充值页面,选择标签页面等,具体实现代码如下:

1,创建

-(UIView *)headerView
{
    CGFloat width = (KscreenW -5*6)/5;
    
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, 60)];
        for (int i = 0; i < 10; i ++) {
            int x = 5 + i % 5 * width + i % 5 * 5;
            int y = i / 5 * 25 + i / 5 * 5;
            
            UIButton *button = [GlobalUI createButtonWithImg:nil title:[NSString stringWithFormat:@"%d",i] titleColor:[UIColor grayColor]];
            button.frame = CGRectMake(x, y, width, 25);
            button.tag = i + 830;
            button.backgroundColor = BackgroundColor;
            button.clipsToBounds = YES;
            button.layer.cornerRadius = 5;
            [button addTarget:self action:@selector(selectedAction:) forControlEvents:UIControlEventTouchUpInside];
            [_headerView addSubview:button];
        
            if (i == 0) {

                self.tmpBtn = button;
                self.tmpBtn.backgroundColor = RGB(44, 190, 247);
                [self.tmpBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
        }
    }
    return _headerView;
}

2,具体实现方法:

-(void)selectedAction:(UIButton *)sender
{
    if (self.tmpBtn == sender) {
        sender.backgroundColor = RGB(44, 190, 247);
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }else{
        sender.backgroundColor = RGB(44, 190, 247);
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _tmpBtn.backgroundColor = BackgroundColor;
        [_tmpBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
    
    self.tmpBtn = sender;
}

3,主要是声明的_tmpBtn

@property(strong, nonatomic) UIButton *tmpBtn;

 

声明一个按钮的实例,在循环创建的时候,指定第0个按钮的选中效果,用_tmpBtn来进行标记,并指定选中的效果,譬如背景色,字体颜色等,

然后在点击事件里面,根据传入的sender的变量来进行匹配,如果是选中的实例按钮,就设置选中样式,反之,把其他的非选中的按钮和已经选中过的按钮进行设置,最后重新赋值下,即可!可能说的有的肤浅,不过大体上就是这麽个意思,见谅!效果图如下:

ios开发之--多个按钮单选效果_背景色

ios开发之--多个按钮单选效果_赋值_02

 

仅做记录! 


作者:稻草人11223