Swift 3.0 label富文本

///富文本,改变字体颜色
func changeTextColor(text: String, color: UIColor, range: NSRange) -> NSAttributedString {
    let attributeStr = NSMutableAttributedString(string: text)
    attributeStr.addAttribute(NSForegroundColorAttributeName, value:color , range: range)

    return attributeStr
}

///改变行间距
func changeTextLineSpace(text: String, lineSpace: CGFloat = 5*UIRate) -> NSAttributedString{
    let attributeStr = NSMutableAttributedString(string: text)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = lineSpace
    attributeStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: text.characters.count))

    return attributeStr
}

OC改变特定字的颜色

//1.特定文字用法
NSString *result = @"我就是喜欢这个平台";
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:result];
    NSRange redRange = NSMakeRange([[attributeStr string] rangeOfString:@"喜欢"].location, [[attributeStr string] rangeOfString:@"喜欢"].length);

    [attributeStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf42e2f) range:redRange]; label.attributedText = attributeStr;

//2.范围用法
 [attributeStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf42e2f) range:NSMakeRange(3, 2)];

//输出结果一样--都是改变了“喜欢”的颜色,但是第一种明显比第二种方便好用

你可能感兴趣的:(UILabel)