在textView中的光标位置插入表情或者文字
方法一:
//获取光标定位的位置
int location = self.textView.selectedRange.location;
//插入前文本框的内容
NSString *textStr = self.textView.text;
//插入后文本框的内容
NSString *resultStr = [NSString stringWithFormat:@"%@%@%@",[textStr substringToIndex:location],username,[textStr substringFromIndex:location]];
//赋值
self.textView.text = resultStr;
补充:
int location = contentText.selectedRange.location;
NSString * textStr = contentText.text;
NSString *str = [faceArr objectAtIndex:sender.tag];
NSString *resultStr = [NSString stringWithFormat:@"%@%@%@",[textStr substringToIndex:location],str,[textStr substringFromIndex:location]];
contentText.text = resultStr;
方法二:
// 将表情插入到当前光标
NSString *str = [faceArr objectAtIndex:sender.tag];
NSRange range = [contentText selectedRange];
NSMutableString *top = [[NSMutableString alloc] initWithString:[contentText text]];
NSString *addName = [NSString stringWithFormat:@"%@",str];
[top insertString:addName atIndex:range.location];
contentText.text = top;
[top release];
当然最后还有把光标置为 添加过内容的后面,所以:
// 插入表情后 光标重新定位(延续方法二)
NSUInteger length = range.location + [str length];
contentText.selectedRange = NSMakeRange(length,0);