在使用UITextView的时候, 如何在光标的位置插入字符 或者 图片? 以下Demo为你解答:
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// NSString *newFaceName = change[@"new"];
NSString *newFaceName = [change objectForKey:NSKeyValueChangeNewKey];
if (!newFaceName || [newFaceName isKindOfClass:[NSNull class]]) {
return;
}
// 在光标位置插入表情
// 1.1 获取当前输入的文字
NSMutableString *string = [NSMutableString stringWithString:_txView.text];
// 1.2 获取光标位置
NSRange rg = _txView.selectedRange;
if (rg.location == NSNotFound) {
// 如果没找到光标,就把光标定位到文字结尾
rg.location = _txView.text.length;
}
// 1.3 替换选中文字
[string replaceCharactersInRange:rg withString:newFaceName];
_txView.text = string;
// 1.4 定位光标
_txView.selectedRange = NSMakeRange(rg.location + newFaceName.length, 0);
}