我有一个被解析的UITextView
,当输入某些字符时,它的属性被更改。不改变文本,只改变描述文本格式的属性。
如果我解析每个字符条目,我基本上是抓取text
,创建一个具有正确格式的属性字符串,并将textview的attributedText
属性设置为我的新属性字符串。这完全破坏了自动更正、双空格快捷键和拼写检查。
如果只在输入某些特殊字符时进行解析,效果会好一点,但会出现奇怪的错误,比如每个句子的第二个单词都大写。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if (text.length == 0) {
return YES;
}
unichar firstCharacterInText = [text characterAtIndex:0];
if (/* special character */) {
[self processTextView];
}
}
- (void) processTextView {
NSString *text = self.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
[attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:kFontRegular size:12.0f] range:NSMakeRange(0, text.length)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor textColor] range:NSMakeRange(0, text.length)];
// set other properties
}
我的问题是:有没有一种方法来改变我的文本视图的文本属性,而不重置textview的attributedText
属性和打破UITextView
的所有这些方便的功能?
在不重置UITextView attributedText (NSAttributedString)属性的情况下突出显示范围内的文本。
let range = NSRange(location: 100, length: 20)
let attribute = [NSAttributedString.Key.backgroundColor: UIColor.yellow]
textStorage.addAttributes(attribute, range: range)
textStorage是UITextView的一个属性
详细说明fatuhoku
的上述评论。你可以调用
func setAttributes(_ attrs: [NSAttributedString.Key: Any]?, range: NSRange)
在文本视图的.textStorage
.
我有同样的问题,事实证明,设置UITextView的attributedText属性触发textViewDidChange:方法。因此,在textViewDidChange:方法中设置attributedText属性创建了一个无限循环。
我做了一个快速修复,我将立即从textViewDidChange:方法返回,每隔一次我调用该方法。它似乎工作正常,但我还需要检查一些。