JLChen
2021-04-30 a5247b61d585627a1a7b1e1f35f34de9f0af9fba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
//  Copyright © 2018年 Zhejiang Dahua Technology Co.,Ltd. All rights reserved.
//
 
import UIKit
 
extension UILabel {
    
    /// 设置Label的富文本
    ///
    /// - Parameters:
    ///   - text: 需要设置的文字
    ///   - font: 字体大小
    ///   - lineSpace: 行距
    ///   - alignment: 对齐方式
    @objc func dh_setAttributedText(text: String?, font: UIFont, lineSpace: CGFloat = 5, alignment: NSTextAlignment = .center) {
        guard text != nil else {
            self.attributedText = nil
            return
        }
        
        let style = NSMutableParagraphStyle()
        style.lineBreakMode = NSLineBreakMode.byWordWrapping
        style.lineSpacing = lineSpace
        style.alignment = alignment
        
        let attributes = [NSAttributedStringKey.paragraphStyle: style,
                          NSAttributedStringKey.font: font]
 
        let attrText = NSMutableAttributedString(string: text!)
        attrText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
        self.attributedText = attrText
    }
    
    
    /// 设置Label的富文本
    ///
    /// - Parameters:
    ///   - text: 需要设置的文字
    ///   - font: 字体大小
    ///   - lineSpace: 行距
    ///   - color: 字体颜色
    func dh_setAttributedText_Normal(text: String?, font: UIFont, color: UIColor, lineSpace: CGFloat = 5) {
        guard text != nil else {
            self.attributedText = nil
            return
        }
        
        let style = NSMutableParagraphStyle()
        style.lineBreakMode = NSLineBreakMode.byWordWrapping
        style.lineSpacing = lineSpace
        
        let attributes = [NSAttributedStringKey.paragraphStyle: style,
                          NSAttributedStringKey.font: font,
                          NSAttributedStringKey.foregroundColor: color]
        
        let attrText = NSMutableAttributedString(string: text!)
        attrText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
        self.attributedText = attrText
    }
    
    
    /// 设置Label的富文本-颜色
    ///
    /// - Parameters:
    ///   - text: 需要设置的文字
    ///   - length: 改变颜色字体节点
    ///   - color1: 前段字体颜色
    ///   - color2: 后段字体颜色
    func dh_setAttributedTextColor(text: String, length: Int, color1: UIColor, color2: UIColor) {
        if text.count >= length {
            let attrStr: NSMutableAttributedString = NSMutableAttributedString.init(string: text)
            attrStr.addAttributes([NSAttributedStringKey.foregroundColor: color1], range: NSMakeRange(0, length))
            attrStr.addAttributes([NSAttributedStringKey.foregroundColor: color2], range: NSMakeRange(length, text.count - length))
            self.attributedText = attrStr
        }
    }
}