在NSAttributed
类型语句中,我希望保留现有的属性值并赋予它一个新的属性值。
问题是replacingOccurrences
只适用于字符串类型,因为我希望每次单词出现在整个句子中时都给出一个新值。
如果将NSAttributedString
更改为字符串类型,则属性值将被删除。我必须保持现有的价值观。
我该怎么做?
最佳答案
为了让这工作顺利进行,
一。首先,您需要找到字符串中存在的所有重复子串的索引。你可以用这个:https://stackoverflow.com/a/40413665/5716829
extension String {
func indicesOf(string: String) -> [Int] {
var indices = [Int]()
var searchStartIndex = self.startIndex
while searchStartIndex < self.endIndex,
let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
!range.isEmpty
{
let index = distance(from: self.startIndex, to: range.lowerBound)
indices.append(index)
searchStartIndex = range.upperBound
}
return indices
}
}
2.接下来,需要将所需的属性应用于每个索引的子字符串,即。
let str = "The problem is that replacingOccurrences Hello is only possible for string types, as I want to give Hello a new value every time Hello the word appears in the entire sentence Hello."
let indices = str.indicesOf(string: "Hello")
let attrStr = NSMutableAttributedString(string: str, attributes: [.foregroundColor : UIColor.blue])
for index in indices
{
//You can write your own logic to specify the color for each duplicate. I have used some hardcode indices
var color: UIColor
switch index
{
case 41:
color = .orange
case 100:
color = .magenta
case 129:
color = .green
default:
color = .red
}
attrStr.addAttribute(.foregroundColor, value: color, range: NSRange(location: index, length: "Hello".count))
}
截图:
如果你还面临任何问题,请告诉我。快乐编码……