< 返回首页

标哥的笔记,是记录在日常学习技术和日常开发中那些年遇到过的坑!本站为新站,原"标哥的技术博客"中的文章会慢慢移到本站,欢迎收藏本站!
在使用本站过程中,有任何建议请联系标哥! 另,承接App开发、网站开发和微信小程序开发!欢迎联系我们


iOS UITextView在光标处插入字符串

 作者:标哥    发布日期:2017-01-13 11:39    阅读量:2323次
 

下面是某次需求中要求在光标处插入所导入的字符串,并且以分开。 这里添加了比较多的逻辑处理,过滤一些字符。另外,在6.0系统上获取selectedRange.location会出现NSNotFound等,因此还处理添加特殊处理。下面的代码是兼容到iOS 6.0的。

#pragma mark -- 更新插入数据到光标处
- (void)updateTextViewTextInsertedString:(NSString *)text {
  if (kIsEmptyString(text)) {
    return;
  }
  
  // 获得光标所在的位置
  NSUInteger location = self.diseaseDescTextView.selectedRange.location;
  if (location == NSNotFound || location >= self.diseaseNameTextField.text.length) {
    if (kIsEmptyString(self.diseaseNameTextField.text)) {
      text = [text substringFromIndex:1];
    }

    NSString *currentText = self.diseaseDescTextView.text;
    if (kIsEmptyString(currentText)) {
      currentText = @"";
    }
    self.diseaseDescTextView.text = [NSString stringWithFormat:@"%@%@",
                                     currentText,
                                     text];
  [self textViewDidChange:self.diseaseDescTextView];
    return;
  }
  
  // 如果光标之前没有内容,去掉前面的逗号
  if (kIsEmptyString([self.diseaseDescTextView.text substringToIndex:location])) {
    if ([text hasPrefix:@","]) {
      if (text.length == 1) {
        text = @"";
      } else {
        text = [text substringFromIndex:1];
      }
    }
  }
  
  if (kIsEmptyString(self.diseaseDescTextView.text)) {
    self.diseaseDescTextView.text = text;
    [self textViewDidChange:self.diseaseDescTextView];
    return;
  }
  
  if (!kIsEmptyString([self.diseaseDescTextView.text substringFromIndex:location])) {
    text = [NSString stringWithFormat:@"%@,", text];
  }
  
  NSString *preText = [self.diseaseDescTextView.text substringToIndex:location];
  if (kIsEmptyString(preText)) {
    preText = @"";
  }
  
  NSString *lastText = [self.diseaseDescTextView.text substringFromIndex:location];
  if (kIsEmptyString(lastText)) {
    lastText = @"";
  }
  
  NSString *result = [NSString stringWithFormat:@"%@%@%@",
                      preText,
                      text,
                      lastText];
  
  self.diseaseDescTextView.text = result;
  [self textViewDidChange:self.diseaseDescTextView];
  
  // 调整光标
  self.diseaseDescTextView.selectedRange = NSMakeRange(location + text.length + 1, 1);
}


承接:ThinkPHP项目开发、网站项目开发、微信项目开发、微信小程序项目开发、App开发,欢迎联系标哥QQ632840804