JLChen
2021-05-18 a869383e163a18cdedcf587383c1eca043129754
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
//
//  Copyright © 2019 dahua. All rights reserved.
//
 
import UIKit
 
extension UITextView {
    
    /// 设置TextView的富文本
    ///
    /// - Parameters:
    ///   - text: 需要设置的文字
    ///   - font: 字体大小
    ///   - lineSpace: 行距
    ///   - alignment: 对齐方式
    @objc func dh_setAttributedText(text: String?, font: UIFont, lineSpace: CGFloat = 5, alignment: NSTextAlignment = .center) {
        guard let string = text else {
            self.attributedText = nil
            return
        }
        
        let style = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle
        style?.lineBreakMode = NSLineBreakMode.byWordWrapping
        style?.lineSpacing = lineSpace
        style?.alignment = alignment
        
        let attributes = [ NSAttributedStringKey.paragraphStyle: style ?? NSMutableParagraphStyle.default,
                           NSAttributedStringKey.font: font ]
        
        let attrText = NSMutableAttributedString(string: string, attributes: attributes)
        self.attributedText = attrText
    }
 
}