swift中yytextview设置双#变色
时间: 2024-03-21 20:39:32 浏览: 13
您可以使用YYText来实现在Swift中设置双#变色。以下是一个示例代码:
```swift
let text = "#This is a #sample text# to demonstrate# how to set double #hashtags# in different color"
let attributedString = NSMutableAttributedString(string: text)
// 设置第一个#的颜色
let firstRange = (text as NSString).range(of: "#")
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: firstRange)
// 找到所有的#号并设置颜色
let pattern = "#(.*?)#"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.count))
for match in matches {
let range = match.range(at: 1)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.green, range: range)
}
// 设置YYTextView的attributedText
textView.attributedText = attributedString
```
这段代码将会把文本中所有的#之间的内容设置为绿色,第一个#设置为红色。您可以根据自己的需要修改颜色或者正则表达式以达到自己想要的效果。