//
//  UILabel+Extension.swift
//  AiKeyboard
//
//  Created by Destiny on 2025/4/25.
//

import UIKit

//设置行间距
extension UILabel {

    /// 设置UILabel的行间距
    /// - Parameter spacing: 行间距的大小
    func setLineSpacing(_ spacing: CGFloat, alignment: NSTextAlignment = .left) {
        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = spacing
        paragraphStyle.alignment = alignment

        let attributedString: NSMutableAttributedString
        if let labelAttributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // 添加行间距属性
        attributedString.addAttribute(
            .paragraphStyle,
            value: paragraphStyle,
            range: NSRange(location: 0, length: attributedString.length)
        )

        self.attributedText = attributedString
    }
}
