更改UITextView上的属性而不重置attributionText属性

Sor*_*lou 5 uikit core-text ios

我有一个UITextView被解析并在键入某些字符时更改其属性.文本不会更改,只会更改描述文本格式的属性.

如果我解析每个字符条目,我基本上抓住它text,创建一个具有正确格式的属性字符串,并将attributedTexttextview 的属性设置为我的新属性字符串.这完全打破了自动更正,双倍空格快捷方式和拼写检查.

如果我只在键入某些特殊字符时进行解析,这会更好一点,但是我会得到奇怪的错误,比如每个句子的第二个单词都是大写的.

- (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 
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有办法改变文本视图的文本属性而不重置textview的attributedText属性并打破所有这些方便的功能UITextView

Lea*_*ner 5

突出显示某个范围内的文本,无需重置UITextView 的attributeText (NSAttributedString) 属性。

let range = NSRange(location: 100, length: 20)
let attribute = [NSAttributedString.Key.backgroundColor: UIColor.yellow]
textStorage.addAttributes(attribute, range: range)
Run Code Online (Sandbox Code Playgroud)

textStorage是 UITextView 的一个属性。


anc*_*jic 0

我遇到了同样的问题,结果发现设置UITextView 的attributeText属性触发了textViewDidChange:方法。因此,从textViewDidChange:方法内部设置attributeText属性创建了一个无限循环。

我做了一个快速修复,每次调用该方法时,我都会立即从textViewDidChange:方法返回。看起来工作正常,但我还需要检查更多。