iOS按钮上展示NSMutableAttributedString全集

- (void)titlelabel
{
    _investBtn.titleLabel.numberOfLines=0;
    _investBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    NSString *string = [NSString stringWithFormat:@"立即投资(%@元起投)\n剩余可投%@元",ZWGT1StartMoney,ZWGT1prgressLabel];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]
                                      initWithString:[NSString stringWithFormat:@"立即投资(%@元起投)\n剩余可投%@",ZWGT1StartMoney,ZWGT1prgressLabel]];
    NSRange range = [string rangeOfString:@"("];  //匹配得到的下标
    NSRange range2 = [string rangeOfString:@")"];  //匹配得到的下标
    NSUInteger i = range.location;
    NSUInteger j = range2.location + 1;
    NSLog(@"%lu",(unsigned long)range.location);//4
    NSLog(@"%lu",(unsigned long)range.length);//1
    NSRange range3 = NSMakeRange(i, j-i);
    NSLog(@"%lu",(unsigned long)range3.location);//4
    NSLog(@"%lu",(unsigned long)range3.length);//10
    NSRange range4 = [string rangeOfString:@""];  //匹配得到的下标
    NSRange range5 = NSMakeRange(range4.location, string.length - range4.location - 1);
    [str addAttribute:NSForegroundColorAttributeName
                value:[UIColor whiteColor]
                range:range5];//用来设置颜色
    [str addAttribute:NSFontAttributeName
                value:[UIFont systemFontOfSize:12.0]
                range:range3];//用来设置字号
    [str addAttribute:NSFontAttributeName
                value:[UIFont systemFontOfSize:15.0]
                range:NSMakeRange(0, 4)];
    [str addAttribute:NSFontAttributeName
                value:[UIFont systemFontOfSize:12.0]
                range:range5];
    
    
    _investBtn.userInteractionEnabled = YES;
    [_investBtn setAttributedTitle:str forState:UIControlStateNormal];
    [_investBtn setBackgroundImage:[UIImage gradientImageFromColors:@[kColorBtnLight, kColorBtnDark] ByGradientType:1 size:_investBtn.frame.size] forState:UIControlStateNormal];
}

下面是效果图:

 

上面是UIButton,对于按钮字的全部更改,换行、居中、部分字体、部分颜色、背景颜色、都可以修改。

 

posted @ 2017-10-27 11:10  预估计  阅读(494)  评论(0编辑  收藏  举报