如何设置一个样式里面的UITextView特定的词吗?

问题描述 投票:0回答:1

我在这我想风格的一个特定的词一个UITextView。我现在面临的问题是,上设置样式的话,它也将在风格这个词的所有其他事件。我只是想这个词的一个特定实例说第一或第三有自定义样式。

考虑本内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.

如果我设置样式为太阳那么两个单词的出现越来越样式施加。

这里是代码

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
1个回答
0
投票

您如何选择要替换的实例?

做到这一点最简单的方法是只维护自己的柜台:

var counter = 0
for word in words {
   if (word == selectedWord) {
     counter += 1
      // myTarget being the first or third or whatever
     let attributesToUse = (counter == myTarget) ? selectedAttributes : normalAttributes
     newText.append(NSMutableAttributedString(string: word + " " , attributes: attributesToUse as [NSAttributedString.Key : Any]))
   } else {
     newText.append(NSMutableAttributedString(string:word + " ", attributes: normalAttributes as [NSAttributedString.Key : Any]))
   }
 }

但是您当然可以通过使用NSAttributedStrings并查找文本范围来变得更加干净。

let myText = NSMutableAttributedString(string: textView.text, attributes: normalAttributes)

// this will only turn up the FIRST occurrence
if let range = myText.range(of: selectedWord) {
    let rangeOfSelected = NSRange(range, in: myText)
    myText.setAttributes(selectedAttributes, range: rangeOfSelected)
}

如果你想使用任意的发生可以概率编写创建的所有范围的阵列的延伸部,然后挑选一个事务,这是一个很好的参考:https://medium.com/@weijentu/find-and-return-the-ranges-of-all-the-occurrences-of-a-given-string-in-swift-2a2015907a0e

定义可能是矫枉过正虽然,也可以修改这些制品,而不是采取在一个int(occuranceNumber)的方法和使用计数器像上面只返回第n次出现的范围内,然后执行相同的,与归属串的事情。

© www.soinside.com 2019 - 2024. All rights reserved.