iOS - 富文本直接设置文字的字体大小和颜色

 

富文本效果图:

 

富文本实现代码:

UILabel *orderSureLabel = [Common lableFrame:CGRectZero title:@"" backgroundColor:[UIColor clearColor] font:[UIFont systemFontOfSize:15] textColor:[UIColor colorWithHexString:@"#666666"]];
    //    orderSureLabel.backgroundColor = [UIColor yellowColor];
    NSMutableAttributedString *orderSureStr = [Common setupAttributeString:@"在主页面下方找到顺道工单,点击“接单”,确认接单。" rangeText:@"顺道工单" textColor:[UIColor colorWithHexString:@"#F34949"]];
    orderSureLabel.attributedText = orderSureStr;
//    orderSureLabel.text = @"在主页面下方找到顺道工单,点击“接单”,确认接单。";
    orderSureLabel.numberOfLines = 0;
    [self addSubview:orderSureLabel];
    [orderSureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(orderLabel.mas_bottom).offset(30);
        make.left.equalTo(self).offset(30);
        make.right.equalTo(self).offset(-30);
        make.centerX.equalTo(self);
    }];

 

富文本实现的分类方法:

#pragma mark - 创建UILabel

+ (UILabel*)lableFrame:(CGRect)frame title:(NSString *)title backgroundColor:(UIColor*)color font:(UIFont*)font textColor:(UIColor*)textColor {
    
    UILabel *lable=[[UILabel alloc]initWithFrame:frame];
    
    lable.text=title;
    
    lable.font=font;
    
    [lable setBackgroundColor:color];
    
    lable.textColor=textColor;
    
    return lable;
    
}

#pragma mark - 富文本设置部分字体颜色

+ (NSMutableAttributedString *)setupAttributeString:(NSString *)text rangeText:(NSString *)rangeText textColor:(UIColor *)color{
    
    NSRange hightlightTextRange = [text rangeOfString:rangeText];
    
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    if (hightlightTextRange.length > 0) {
        
        [attributeStr addAttribute:NSForegroundColorAttributeName
                 
                 value:color
                 
                 range:hightlightTextRange];
        
        [attributeStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14.0f] range:hightlightTextRange];
        
        return attributeStr;
        
        }else {
            
            return [rangeText copy];
            
            }
}

 

posted @ 2019-03-12 16:03  公羽寒  阅读(1834)  评论(0编辑  收藏  举报