在 Swift 4 和 iOS 11 中,您可以使用以下两种方法之一来解决您的问题。
#1。使用NSMutableAttributedStringreplaceCharacters(in:with:)方法
NSMutableAttributedString 有一个名为replaceCharacters(in:with:) 的方法。 replaceCharacters(in:with:) 有以下声明:
用给定属性字符串的字符和属性替换给定范围内的字符和属性。
func replaceCharacters(in range: NSRange, with attrString: NSAttributedString)
下面的 Playground 代码展示了如何使用 replaceCharacters(in:with:) 来将 NSMutableAttributedString 实例的子字符串替换为新的 NSMutableAttributedString 实例:
import UIKit
// Set initial attributed string
let initialString = "This is the initial string"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let mutableAttributedString = NSMutableAttributedString(string: initialString, attributes: attributes)
// Set new attributed string
let newString = "new"
let newAttributes = [NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue]
let newAttributedString = NSMutableAttributedString(string: newString, attributes: newAttributes)
// Get range of text to replace
guard let range = mutableAttributedString.string.range(of: "initial") else { exit(0) }
let nsRange = NSRange(range, in: mutableAttributedString.string)
// Replace content in range with the new content
mutableAttributedString.replaceCharacters(in: nsRange, with: newAttributedString)
#2。使用NSMutableStringreplaceOccurrences(of:with:options:range:)方法
NSMutableString 有一个名为replaceOccurrences(of:with:options:range:) 的方法。 replaceOccurrences(of:with:options:range:) 有以下声明:
用另一个给定字符串替换给定范围内所有出现的给定字符串,返回替换次数。
func replaceOccurrences(of target: String, with replacement: String, options: NSString.CompareOptions = [], range searchRange: NSRange) -> Int
下面的 Playground 代码展示了如何使用 replaceOccurrences(of:with:options:range:) 来将 NSMutableAttributedString 实例的子字符串替换为新的 NSMutableAttributedString 实例:
import UIKit
// Set initial attributed string
let initialString = "This is the initial string"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let mutableAttributedString = NSMutableAttributedString(string: initialString, attributes: attributes)
// Set new string
let newString = "new"
// Replace replaceable content in mutableAttributedString with new content
let totalRange = NSRange(location: 0, length: mutableAttributedString.string.count)
_ = mutableAttributedString.mutableString.replaceOccurrences(of: "initial", with: newString, options: [], range: totalRange)
// Get range of text that requires new attributes
guard let range = mutableAttributedString.string.range(of: newString) else { exit(0) }
let nsRange = NSRange(range, in: mutableAttributedString.string)
// Apply new attributes to the text matching the range
let newAttributes = [NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue]
mutableAttributedString.setAttributes(newAttributes, range: nsRange)