我有一個帶有淺灰色文本的 UITextView。
我希望每條新行的顏色始終設定為黑色,這樣我就可以確定新行始終為黑色,而不管前一行的顏色如何
例如
這是第一行 --> foregroundColor.lightgray
\n
_ --> 這個新的空行必須有foregroundColor.black
為此,我嘗試在每次按 Enter 時更改 foregroundColor 屬性(新行 \n)
在 UITextView 的協調員中
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
let customAttrributes : [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: UIColor.black
]
if textView.selectedTextRange != nil {
textView.textStorage.addAttributes(customAttrributes, range: NSRange(location: textView.selectedRange.location, length: 1))
這會回傳“越界”錯誤,我不明白為什么。我想這是因為沒有字符,所以長度 1 被認為不存在。但是是否可以使用黑色文本屬性設定新的空白行,或者您是否必須等待插入一些字符?
謝謝!
uj5u.com熱心網友回復:
最簡單的方法之一是設定typingAttributes。例如,您可以使用此答案檢測新行。所以讓我們說一下我們開始使用 .lightGray 顏色列印的內容。首先我們設定:textView.typingAttributes = [.foregroundColor: UIColor. lightGray]. 我們應該在新行的開頭切換到黑色。
var previousRect = CGRect.zero
func textViewDidChange(_ textView: UITextView) {
let pos = textView.endOfDocument
let currentRect = textView.caretRect(for: pos)
self.previousRect = self.previousRect.origin.y == 0.0 ? currentRect : self.previousRect
if currentRect.origin.y > self.previousRect.origin.y {
textView.typingAttributes = [.foregroundColor: UIColor.black]
}
self.previousRect = currentRect
}
uj5u.com熱心網友回復:
這是 NSAttributedString 中具有不同文本和 textColor 的兩行的示例:
let attributedString = NSMutableAttributedString(attributedString: NSAttributedString(string: "First Line", attributes: [.font: UIFont.systemFont(ofSize: 16, weight: .semibold), .foregroundColor: UIColor.lightGray]))
attributedString.append(NSAttributedString(string: "Second Line", attributes: [.foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 16, weight: .semibold)]))
textView.attributedText = attributedString
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516585.html
