Вы должны использовать shouldChangeTextInRange
.Это потому, что вам нужен диапазон, чтобы найти место, где вы хотите, чтобы текст был изменен.
UITextView позволяет сохранить ваш стиль в textView.attributedString
.
. Решение состоит в том, чтобы получить строку атрибута textView и заменить в нем нужную подстроку.с измененным или стилизованным текстом.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText]; //gets textView style string
NSRange selectedTextRange = [textView selectedRange];
NSString *selectedString = [textView textInRange:textView.selectedTextRange]; //our selected text
//lets say you always want to make selected text bold
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize];
NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedString attributes:boldAttr]; //make attributed string of our selectedtext
[textViewText replaceCharactersInRange:range withAttributedString:attributedText]; // replace
textView.attributedText = textViewText;
return false;
}