在textView中的光标位置插入表情或者文字   

 
 
刚在写项目遇到在textView的光标位置插入表情,则查了查得出结论:
方法一:

    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);
posted on 2015-08-25 09:57  懿燚  阅读(192)  评论(0编辑  收藏  举报