美文网首页
富文本改变目标文字的大小与颜色

富文本改变目标文字的大小与颜色

作者: 奋斗的遗忘人 | 来源:发表于2023-05-05 08:58 被阅读0次
extension String {
    
    /// 富文本改变固定文字的颜色加粗以及大小
    /// - Parameters:
    ///   - text: 主文本内容
    ///   - highlightText: 目标文字
    ///   - highlightColor: 目标文字颜色
    ///   - highlightSize: 目标文字大小
    ///   - textColor: 主文本文字颜色
    ///   - fontSize: 主文本文字大小
    /// - Returns:  返回富文本
    public static func attributedString(with text: String, highlightText: String, highlightColor: UIColor, highlightSize: CGFloat, textColor: UIColor = .black, fontSize: CGFloat = 14) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: text, attributes: [
            .foregroundColor: textColor,
            .font: UIFont.systemFont(ofSize: fontSize)
        ])
        if let range = text.range(of: highlightText) {
            let nsRange = NSRange(range, in: text)
            attributedString.addAttributes([
                .foregroundColor: highlightColor,
                .font: UIFont.systemFont(ofSize: highlightSize)
            ], range: nsRange)
        }
        return attributedString
    }
    
    /// 富文本改变固定文字的颜色加粗以及大小
    /// - Parameters:
    ///   - string: 主文本内容
    ///   - targetSubstring: 目标文字
    ///   - color: 目标文字颜色
    ///   - fontSize: 目标文字大小
    ///   - isBold: 是否加粗
    ///   - lineSpacing: 行间距
    /// - Returns: 返回富文本
    public static func attributedString(for string: String, targetSubstring: String, color: UIColor, fontSize: CGFloat, isBold: Bool, lineSpacing:CGFloat) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: string)
        let range = (string as NSString).range(of: targetSubstring)
        let font: UIFont = isBold ? .boldSystemFont(ofSize: fontSize) : .systemFont(ofSize: fontSize)
        attributedString.addAttribute(.foregroundColor, value: color, range: range)
        attributedString.addAttribute(.font, value: font, range: range)
        //行间距
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        attributedString.addAttributes([.paragraphStyle:paragraphStyle], range: NSRange(location: 0, length: string.count - 1))
        
        return attributedString
    }
  
}

相关文章

网友评论

      本文标题:富文本改变目标文字的大小与颜色

      本文链接:https://www.haomeiwen.com/subject/clifsdtx.html