我正在尝试在我的应用中创建一个 RichTextEditor。
用户在编辑时可以同时更改前景色和背景色。
这是我设置 typingAttributes 的方法:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
self.setTypingColor(foregroundColor: self.foregroundColor, backgroundColor: self.backgroundColor)
return true
}
但我发现如果用户输入\n
,编辑器也会给整行应用背景色。
这就是我想要的。
也就是说,我希望它只将这些颜色应用于字符,而不是 \n
、\t
或 \r
。
有没有办法不用我自己创建 AttributedString
来做到这一点?
最佳答案
在简单的情况下,这样的事情可能会奏效。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" { // better matching required
self.setTypingColor(foregroundColor: .clear, backgroundColor: .clear)
} else {
self.setTypingColor(foregroundColor: self.foregroundColor, backgroundColor: self.backgroundColor)
}
return true
}
但当用户将字符串粘贴到您的 TextView 中时,问题可能会持续存在,在这种情况下,我认为您可能必须开始处理属性字符串。
关于ios - 防止 UITextView.typingattributes 在 Swift 中的换行符 (\n) 上应用 backgroundColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47474307/