【发布时间】:2019-12-04 18:49:06
【问题描述】:
我有一个 UITextView,我试图在其中设置特定单词的样式。我面临的问题是,在为单词设置样式时,它还将样式应用于单词的所有其他出现。我只希望单词 say first 或 third 的一个特定实例具有自定义样式。
考虑 UITextView 中存在的文本。
Sunset is the time of day when our sky meets the outer space solar winds.
There are blue, pink, and purple swirls, spinning and twisting, like clouds of balloons caught in
a whirlwind. The sun moves slowly to hide behind the line of horizon, while the
moon races to take its place in prominence atop the night sky. People slow to a crawl,
entranced, fully forgetting the deeds that must still be done. There is a coolness, a
calmness, when the sun does set.
如果我将样式设置为 sun,那么两个单词的出现都会应用样式。
这里是代码
let normalAttr = [NSAttributedString.Key.font: UIFont(name: "Oswald", size: 19.0), NSAttributedString.Key.paragraphStyle : style]
let customAttr = [NSAttributedString.Key.font: UIFont(name: "Oswald", size: 19.0), NSAttributedString.Key.foregroundColor: UIColor.red]
let words = textView.text.components(separatedBy: " ")
let newText = NSMutableAttributedString()
for word in words {
if (word == selectedWord) {
newText.append(NSMutableAttributedString(string: word + " " , attributes: selectedAttributes as [NSAttributedString.Key : Any]))
} else {
newText.append(NSMutableAttributedString(string:word + " ", attributes: normalAttributes as [NSAttributedString.Key : Any]))
}
}
textView.attributedText = newText
我只想将样式应用于一个单词,有什么帮助吗?
【问题讨论】:
标签: ios swift string xcode uitextview