美文网首页
iOS 快速设置多个按钮切换选中状态

iOS 快速设置多个按钮切换选中状态

作者: 小的小碰撞 | 来源:发表于2017-05-31 15:09 被阅读0次
- (void)addView{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    UZGAddressTypeViewModel *model=[[UZGAddressTypeViewModel alloc]init];
    model.type=@"公司";
    model.selectImageName=@"公司";
    model.unSelectImageName=@"公司灰色";
    [array addObject:model];
    
    model=[[UZGAddressTypeViewModel alloc]init];
    model.type=@"住宅";
    model.selectImageName=@"住宅";
    model.unSelectImageName=@"住宅灰";
    [array addObject:model];
    
    model=[[UZGAddressTypeViewModel alloc]init];
    model.type=@"学校";
    model.selectImageName=@"学校";
    model.unSelectImageName=@"学校灰";
    [array addObject:model];
    
    model=[[UZGAddressTypeViewModel alloc]init];
    model.type=@"其他";
    model.selectImageName=@"其他亮";
    model.unSelectImageName=@"其他";
    [array addObject:model];
    
    CGFloat width=40;
    CGFloat height=CGRectGetHeight(self.frame);
    CGFloat space=14;
    for (int i=0;i<array.count;i++) {
        UZGAddressTypeViewModel *model=[[UZGAddressTypeViewModel alloc]init];
        model=array[i];
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake((space+width)*i,0,width,height)];
        [btn setImage:[UIImage imageNamed:model.unSelectImageName] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:model.selectImageName]   forState:UIControlStateSelected];
        [btn setImage:[UIImage imageNamed:model.selectImageName]   forState:UIControlStateHighlighted];
        [btn addTarget:self action:@selector(buttonTouchClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {//设置默认选中按钮
            [self buttonTouchClick:btn];
           // 或者
           //   publishButton.isSelected = true
           //    selectedBtn = publishButton
             
        }
        [self addSubview:btn];
    }
}
- (void)buttonTouchClick:(UIButton *)btn{
    //   1.设置当前按钮的状态
    self.currentSelectButton.selected=NO;
    //  2.设置传入按钮的为选中状态
    btn.selected=YES;
    // 3. 设置当前按钮为传入的按钮
    self.currentSelectButton=btn;
}


///// 第二种 

#pragma mark - Setter

- (void)setSelectIndex:(NSInteger)selectIndex
{
    // 先把上次选择的item设置为可用
    UIButton *lastItem = _items[_selectIndex];
    lastItem.enabled = YES;
    // 再把这次选择的item设置为不可用
    UIButton *item = _items[selectIndex];
    item.enabled = NO;
    _selectIndex = selectIndex;
}


相关文章

网友评论

      本文标题:iOS 快速设置多个按钮切换选中状态

      本文链接:https://www.haomeiwen.com/subject/kqhjfxtx.html