UITextView 光标定位

在使用UITextView的时候, 如何在光标的位置插入字符 或者 图片? 以下Demo为你解答:

应用背景:键盘自定义emoji表情

#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;
      }
      // 在光标位置插入表情
      [self textWithString:newFaceName];
//    [self attributedTextWithString:newFaceName];
    
}

#pragma mark - text && attributedText
- (void)textWithString:(NSString *)newFaceName
{

      // 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);
}

// _txView.attributedText  && 虽然能在发送微博时显示图片
// 但是由于plist 文件中的 png名字与官方不一样
// 所以发送出去的内容微博不能识别 emoji 表情
- (void)attributedTextWithString:(NSString *)newFaceName
{

      // 1.1 获取当前输入的文字
      NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
      // 1.1.1 拼接之前的文字(图片和文字)
      [attributedText appendAttributedString:_txView.attributedText];
    
      // 1.2 获取光标位置
      NSRange rg = _txView.selectedRange;
      if (rg.location == NSNotFound) {
        
        // 如果没找到光标,就把光标定位到文字结尾
        rg.location = _txView.text.length;
      }
    
      // 1.3 替换选中文字
      // 1.3.1 加载图片
      NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
      attachment.image = [UIImage imageNamed:newFaceName];
      CGFloat attchWH = _txView.font.lineHeight;
      attachment.bounds = CGRectMake(0, -3, attchWH, attchWH);
    
      NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment:attachment];
    
      // 1.3.2 拼接图片
      [attributedText insertAttributedString:attributedString atIndex:rg.location];
    
      // 1.3.3 设置字体大小,_txView.font--> null ?!
  //    NSRange range = NSMakeRange(0, attributedText.length);
  //    [attributedText addAttribute:NSFontAttributeName value:_txView.font range:range];
    
      // 1.3.4 替换文字
      _txView.attributedText = attributedText;
    
      // 1.4 定位光标
      _txView.selectedRange = NSMakeRange(rg.location + 1, 0);
}

利用KVO监听输入的emoji表情

if (!_faceView) {
  _faceView = [[FaceView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0)];

  [_faceView.faceImgView addObserver:self forKeyPath:kFaceNameKVO options:NSKeyValueObservingOptionNew context:nil];
}

部分Demo:GitHub FaceViewDemo


posted @ 2018-09-07 17:08  光是光光的光呐  阅读(467)  评论(0编辑  收藏  举报