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

- (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;icount;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];

        }

        [self addSubview:btn];

    }

}

- (void)buttonTouchClick:(UIButton *)btn{

    self.currentSelectButton.selected=NO;

    btn.selected=YES;

    self.currentSelectButton=btn;

}

你可能感兴趣的:(iOS开发)