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
}
}
富文本改變目標文字的大小與顏色
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 自己創建一個NSString的類別:創建一個回調block:typedef void(^AttributedBlo...
- Swift中對UILable的文字大小、顏色、行間距、富文本屬性等設置 goodsLab.text = "潛水艇防...
- 1、在一段字符串中,改變多個不一樣的字符的大小、顏色 2、找出特定字符在整個字符串中的位置(所有位置:可能包含多個...
- UIAlertController*alert = [UIAlertControlleralertControll...