循环创建button,选中按钮改变颜色,其他按钮恢复原状

循环创建button

#define Start_X          15.0f      // 第一个按钮的X坐标
#define Start_Y          0.0f     // 第一个按钮的Y坐标
#define Width_Space      13.0f      // 2个按钮之间的横间距
#define Height_Space     20.0f     // 竖间距
#define Button_Height   33.0f    // 高
#define Button_Width    75.0f    // 宽
@interface Fiat_MainVC ()
{
    //创建一个全局变量button
    UIButton *mapBtn;
}
-(void)initFliterVIew
{
    [self addButtonS:self.dataArray.count];
}
-(void)addButtonS:(NSInteger)number
{
    ButtonNumber=number;
    for (int i = 0 ; i < number; i++) {
        Fiat_SourceModel *model=self.dataPayments[i];
        NSInteger index = i % 4;
        NSInteger page = i / 4;
        // 圆角按钮
        mapBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
          mapBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        mapBtn.tag = model.sourceID.intValue;//这句话不写等于废了
        [mapBtn setTitle:model.sourceName forState:UIControlStateNormal];
        mapBtn.frame = CGRectMake(index * (Button_Width + Width_Space) + Start_X, page  * (Button_Height + Height_Space)+Start_Y, Button_Width, Button_Height);
        mapBtn.layer.borderWidth=1;
        mapBtn.layer.borderColor=Until_BorderColor.CGColor;
        mapBtn.clipsToBounds=YES;
        mapBtn.layer.cornerRadius=4;
        [mapBtn setTitleColor:Until_BorderColor forState:UIControlStateNormal];
        [mapBtn setBackgroundColor:[UIColor whiteColor]];
        mapBtn.selected=NO;
        [self.ButtonVIew addSubview:mapBtn];
        //按钮点击方法
        [mapBtn addTarget:self action:@selector(mapBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}

#pragma mark - 点击方法

//点击按钮方法,这里容易犯错  点击当前按钮改变当前按钮状态,其他按钮回归原状态
-(void)mapBtnClick:(UIButton *)sender{
    if (sender != mapBtn) {
        mapBtn.layer.borderColor=Until_BorderColor.CGColor;
        [mapBtn setTitleColor:Until_BorderColor forState:UIControlStateNormal];
        mapBtn.selected = NO;
        mapBtn = sender;
    } //这个if是网上抄的,有点神奇
    
    mapBtn.selected = YES;
    
        if(mapBtn.selected)
        {
            SelectPayment=[NSString stringWithFormat:@"%ld",(long)mapBtn.tag];
            mapBtn.layer.borderColor=Until_BlueColor.CGColor;
            [mapBtn setTitleColor:Until_BlueColor forState:UIControlStateNormal];
        }
    
  
    NSLog(@"%ld",sender.tag);
}

你可能感兴趣的:(循环创建button,选中按钮改变颜色,其他按钮恢复原状)