如何在UITextView中输入不同颜色的字符串使用不同的语言



我想选择颜色,然后使用不同的语言更改当前输入的UITextView的文本颜色

但是我遇到了以下问题

1.找不到最后输入的文本

演示图片

例如,在这种情况下,我还没有确认输入的文本,但它已经执行了方法

- (BOOL)textView:(UITextView *) textView shouldChangeTextInRange: (NSRange)range replacementText: (NSString *)text

我想它是第一个创建一系列字符,确认输入单词的选择,然后将其替换为

但是,我不需要这个输入字符范围,这会影响NSRange参数。我需要更改单词的颜色

所以我把颜色函数改成了textViewDidChange方法,但它导致我删除了崩溃的

2.为什么除英语以外的其他语言不执行方法

- (void)insertText:(NSString *)text

这是我的演示链接https://github.com/xueyefengbao/Demo.git

谁可以帮助我解决问题或修改我在演示中提到的功能?

非常感谢:)

根据trungduc的建议,我更改了代码

仍然发现一些小问题

错误的

正确的

无法连续进入

连续输入错误

回答您的问题。

  • 找不到最后输入的文本-删除前似乎忘记重置lastRange。但是你不再使用它,所以我们可以忽略它。

  • 为什么除英语以外的其他语言不执行方法这是因为在您的语言中,在某些情况下,当您输入字符时,它并不总是向字符串中添加字符。实际上,它用另一个字符替换了最后一个字符。它使您从shouldChangeTextInRange获得的lastRange超出了textView上当前文本的范围。我的解决方案是在使用[attributedString addAttribute:NSForegroundColorAttributeName value:self.currentColor range:self.lastRange];之前,您应该检查并更正self.lastRange

您可以尝试用下面的代码替换您的方法。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if (text.length == 0) {
self.lastRange = NSMakeRange(0, 0); // Reset lastRange when deleting
return YES;
}
if ([text isEqualToString:@"n"]) {
[textView resignFirstResponder];
}
BOOL result = [self doesFit:textView string:text range:range];
if (result) {
self.lastRange = NSMakeRange(range.location, text.length);
}
return result;
}
- (void)resetCorrectFontStyle:(UITextView *)textView  {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = (textView.textContainer.size.height - (textView.font.lineHeight)*23)/23;
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, textView.attributedText.length)];
// Check if lastRange can't be used with current text, correct location of lastRange
if (_lastRange.length + _lastRange.location > textView.text.length) {
_lastRange = NSMakeRange(_lastRange.location - 1, _lastRange.length);
}
[attributedString addAttribute:NSForegroundColorAttributeName value:self.currentColor range:self.lastRange];
_keyboardTextView.attributedText = attributedString;
}

希望这能有所帮助。

最新更新