我有一個 UITextView,我想在其中為文本添加背景(突出顯示它)。我希望突出顯示除新行之外的所有內容。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
只有當它有背景時,您才能在 上列舉 ( enumerate(_:in:option:))NSAttributedString.Key.backgroundColor以查找更改。然后,您可以使用正則運算式或 while 回圈range(of:)來查找它們的位置,并洗掉.backgroundColor它們:
使用 Playgrounds 上的示例代碼:
func highlights() -> UITextView {
let tv = UITextView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
tv.backgroundColor = .orange
let text = "Hello world! How are you today?\nLet's start do some testing.\nAnd this is a long paragraph just to see it to the end of the line."
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 15.0),
.backgroundColor: UIColor.systemPink]
let first = NSAttributedString(string: text, attributes: attributes)
let second = NSMutableAttributedString(string: text, attributes: attributes)
guard let regex = try? NSRegularExpression(pattern: "\n", options: []) else { return tv }
second.enumerateAttribute(.backgroundColor, in: NSRange(location: 0, length: second.length), options: []) { attribute, range, stop in
guard attribute as? UIColor != nil else { return }
guard let subrange = Range(range, in: second.string) else { return }
let substring = String(second.string[subrange])
let ranges = regex.matches(in: substring, options: [], range: NSRange(location: 0, length: substring.utf16.count))
ranges.forEach {
second.removeAttribute(.backgroundColor, range: $0.range)
}
}
let total = NSMutableAttributedString()
total.append(first)
total.append(NSAttributedString(string: "\nNormal Text, nothing to see here\n"))
total.append(second)
total.append(NSAttributedString(string: "\nNormal Text, nothing to see here\n"))
tv.attributedText = total
return tv
}
let tv = highlights()

旁注:如果您在 string 中"\n \n",我沒有處理這種情況,這可能需要對正則運算式模式進行一些更改。經過快速測驗,然后NSRegularExpression(pattern: "\n(\\s \n)*", options: [])可能會成功。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405070.html
標籤:
