В Swift 4 и iOS 11 вы можете использовать один из 2 следующих способов для решения вашей проблемы.
# 1.Использование метода NSMutableAttributedString
replaceCharacters(in:with:)
NSMutableAttributedString
имеет метод с именем replaceCharacters(in:with:)
.replaceCharacters(in:with:)
имеет следующее объявление:
Заменяет символы и атрибуты в заданном диапазоне на символы и атрибуты данной приписанной строки.
func replaceCharacters(in range: NSRange, with attrString: NSAttributedString)
TheПриведенный ниже код игровой площадки показывает, как использовать 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.Использование метода NSMutableString
replaceOccurrences(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
Приведенный ниже код игровой площадки показывает, как использовать 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)