// // UILabel+Ex.swift // TSLiveWallpaper // // Created by 100Years on 2024/12/20. // public extension UILabel { /// 快速创建 UILabel /// - Parameters: /// - text: 文本内容 /// - font: 字体 /// - textColor: 文本颜色 /// - textAlignment: 文本对齐方式 /// - numberOfLines: 行数,默认 1 /// - backgroundColor: 背景颜色 /// - adjustsFontSizeToFitWidth: 是否自适应宽度,默认 false /// - cornerRadius: 圆角,默认 0 /// - Returns: 配置好的 UILabel 实例 static public func createLabel(text: String? = nil, font: UIFont? = nil, textColor: UIColor? = nil, textAlignment: NSTextAlignment = .left, numberOfLines: Int = 0, backgroundColor: UIColor? = nil, adjustsFontSizeToFitWidth: Bool = false, cornerRadius: CGFloat = 0) -> UILabel { let label = UILabel() label.setUpLabel( text: text, font: font, textColor: textColor, textAlignment: textAlignment, numberOfLines: numberOfLines, backgroundColor: backgroundColor, adjustsFontSizeToFitWidth: adjustsFontSizeToFitWidth, cornerRadius: cornerRadius ) return label } public func setUpLabel(text: String? = nil, font: UIFont? = nil, textColor: UIColor? = nil, textAlignment: NSTextAlignment = .left, numberOfLines: Int = 0, backgroundColor: UIColor? = nil, adjustsFontSizeToFitWidth: Bool = false, cornerRadius: CGFloat = 0) { let label = self // 设置文本内容 label.text = text // 设置字体 if let font = font { label.font = font } // 设置文本颜色 if let textColor = textColor { label.textColor = textColor } // 设置文本对齐方式 label.textAlignment = textAlignment //阿拉伯语适配 if kIsRTL { label.semanticContentAttribute = .forceRightToLeft if textAlignment == .left { label.textAlignment = .right }else if textAlignment == .right { label.textAlignment = .left } } // 设置行数 label.numberOfLines = numberOfLines // 设置背景颜色 if let backgroundColor = backgroundColor { label.backgroundColor = backgroundColor } // 设置是否自适应宽度 label.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth // 设置圆角 if cornerRadius > 0 { label.layer.cornerRadius = cornerRadius label.layer.masksToBounds = true } } /// 设置行间距 /// - Parameters: /// - lineSpacing: 行间距 /// - alignment: 对齐方式(默认为左对齐) func setLineSpacing(_ lineSpacing: CGFloat) { guard let text = self.text else { return } // 创建 NSMutableAttributedString let attributedString = NSMutableAttributedString(string: text) // 创建段落样式 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpacing paragraphStyle.alignment = self.textAlignment // 应用段落样式到整个文本 attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length)) // 设置属性文本 self.attributedText = attributedString } }