ios - 防止 UITextView.typingattributes 在 Swift 中的换行符 (\n) 上应用 backgroundColor

标签 ios swift uitextview

我正在尝试在我的应用中创建一个 RichTextEditor。

用户在编辑时可以同时更改前景色和背景色。

这是我设置 typingAttributes 的方法:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    self.setTypingColor(foregroundColor: self.foregroundColor, backgroundColor: self.backgroundColor)

    return true
}

但我发现如果用户输入\n,编辑器也会给整行应用背景色。

enter image description here

这就是我想要的。

enter image description here

也就是说,我希望它只将这些颜色应用于字符,而不是 \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/

相关文章:

ios - Xcode Swift 以编程方式将 UITextfield X 位置设置为中心

ios - 一段时间后从 NSMutableDictionary 中删除对象

ios - 使用消耗品型号 IAP iOS 购买 IAP 后,从多张照片中的精选照片中删除 Logo

ios - 在 Swift 中将整数转换为 NSData

swift - 没有childByAutoId()是否可以获取数据库引用。 key ?

iphone - 如何将自定义标签 View 添加到uitextview?

ios - 在自动布局中隐藏不断增长的 UItextview 的键盘。如何克服这个?

objective-c - UIViewController 中的 UIViewController

swift - 当 UIScreen 亮度改变时添加动画淡入淡出效果(Swift)

ios - 替换UITextView中的文本运行缓慢