Skip to main content
 首页 » 操作系统

ios之在 Swift 的 uitextview 中查找单词或字符数

2024年01月01日42cyq1162

我想学习在 uitextview 上搜索单词或字符数。

我使用了:rangeOfIndex(uitextfield.text)

但这只是找到我一个,即第一个。如果 uitextview 包含 4 次相同的单词,则 rangeOfIndex 仅首先显示给我。

谢谢。

请您参考如下方法:

试试这个

 let searchString = "abc" 
 let baseString = "This is DEMO APP abc \"abc\" more th. abcabcABCAbc." 
 
 let attributed = NSMutableAttributedString(string: baseString) 
 
 var error: NSError? 
 let regex = NSRegularExpression(pattern: searchString, options: .CaseInsensitive, error: &error) 
 
 if let regexError = error { 
println("Oh no! \(regexError)") 
  }    
 else { 
    for match in regex.matchesInString(baseString, options: NSMatchingOptions.allZeros, range: NSRange(location: 0, length: baseString.utf16Count)) as [NSTextCheckingResult] { 
    attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: match.range) 
  } 
 
textView.attributedText = attributed 
}