我有一个UITextView
与许多不同的单词相邻。当用户输入的屏幕,我要开始凸显一些话,如:如何在Swift中逐个更改我的UITextView中某些单词的样式?
第一是他看到的是文本的墙:
one two three #four five six #seven eight nine ten
eleven #twelve thirteen fourteen fifteen sixteen
some other words #example test whatever #some thing
然后,在一秒钟后,这个词four
会改变风格(颜色),所以,他会看到:
one two three #FOUR five six #seven eight nine ten
eleven #twelve thirteen fourteen fifteen sixteen
some other words #example test whatever #some thing
然后,在一秒钟后,另一个词将突出(并加入已经着色four
):
one two three #FOUR five six #SEVEN eight nine ten
eleven #twelve thirteen fourteen fifteen sixteen
some other words #example test whatever #some thing
等等。所以几秒钟后用户会看到:
one two three #FOUR five six #SEVEN eight nine ten
eleven #TWELVE thirteen fourteen fifteen sixteen
some other words #EXAMPLE test whatever #SOME thing
然后文本应该保持这样。 我该如何做到这一点?
我想过通过单词循环并检查它们是否等于预定义的单词,但我不知道如何咬它 - 你能帮我一下吗?
=====编辑
因此,为了使事情变得更容易为我自己,我决定与#
符号来标记高亮的话。
我有延伸突出的是,在与TextView的开头#
所有单词:
extension UITextView {
func formatTextInTextView() {
self.isScrollEnabled = false
let selectedRange = self.selectedRange
let text = self.text
let font = UIFont(name: "AppleSDGothicNeo-Light", size: 16.0)
let titleDict: NSDictionary = [NSFontAttributeName: font!]
// This will give me an attributedString with the desired font
let attributedString = NSMutableAttributedString(string: text!, attributes: titleDict as! [String : AnyObject])
let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
let matches = regex!.matches(in: text!, options: [], range: NSMakeRange(0, (text?.characters.count)!))
for match in matches {
let matchRange = match.rangeAt(0)
let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor]
attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange)
}
self.attributedText = attributedString
self.selectedRange = selectedRange
self.isScrollEnabled = true
}
}
,但我不知道如何分开显示的每个字有一秒的延迟
您对循环的想法是正确的。尝试一些东西。用一些相关的代码更新你的问题,至少展示一些基本的尝试。清楚地描述你需要帮助。 – rmaddy
@maddy,我编辑了我的问题,谢谢指出! – user3766930
由于您使用的是正则表达式,该代码一次突出显示所有单词。你需要一些方法来创建一个你想要突出显示的单词列表(数组),然后遍历该数组。对于每个单词,您随后都会找到该单词的所有匹配项。 – rmaddy