美文网首页
iOS 设置button按钮的选中和非选中样式

iOS 设置button按钮的选中和非选中样式

作者: 可乐小子 | 来源:发表于2023-10-26 18:10 被阅读0次

btn= [[UIButton alloc]initWithFrame:CGRectMake((buttonWidth + 16)*i+16, 15, buttonWidth, buttonHeght)];
btn.backgroundColor = White_Color;
[btn addTarget:self action:@selector(moneyBtnClick:) forControlEvents:UIControlEventTouchUpInside];

            btn.titleLabel.font = [UIFont systemFontOfSize:12];
            NSString *string =[NSString stringWithFormat:@"%@\n%@",rechargeMoney,giveMoney];
            btn.titleLabel.lineBreakMode = 0;//这句话很重要,不加这句话加上换行符也没用
            NSRange font_range = [string rangeOfString:string];
            NSMutableAttributedString *mAttStri = [[NSMutableAttributedString alloc] initWithString:string];
            [mAttStri addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:Text_LightGray_Color} range:font_range];
            [btn setAttributedTitle:mAttStri forState:UIControlStateNormal];
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            
            NSMutableAttributedString*nAttStri = [[NSMutableAttributedString alloc] initWithString:string];
            [nAttStri addAttribute:NSForegroundColorAttributeName value:Red_Color range:NSMakeRange(0, string.length)];
            [nAttStri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:font_range];
            [btn setAttributedTitle:nAttStri forState:UIControlStateSelected];

-(void)moneyBtnClick:(UIButton *)button
{
for (UIButton * btn in button.superview.subviews) {
if([btn isKindOfClass:[UIButton class]])
{
btn.selected = NO;

        btn.layer.borderWidth = 1.0;
    }
    
}

button.selected = YES;
button.layer.borderWidth = 0;

//    NSInteger index = button.tag  - 2000;



if (button.currentTitle ==nil || [button.currentTitle isEqualToString:@""]) {
    NSAttributedString *str = button.currentAttributedTitle;
    
    NSString *string = [str string];
    
    NSArray *tempArr = [string componentsSeparatedByString:@"\n"];
    
    _moneyStr = [tempArr[0] componentsSeparatedByString:@"元"][0];
}else{
    
    NSString * str = button.currentTitle;
    _moneyStr = [str componentsSeparatedByString:@"元"][0];
}


self.textField.text = _moneyStr;
}

相关文章

网友评论

      本文标题:iOS 设置button按钮的选中和非选中样式

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