UITextView在光标处插入字符串

UITextView在光标处插入字符串


下面是某次需求中要求在光标处插入所导入的字符串,并且以分开。
这里添加了比较多的逻辑处理,过滤一些字符。另外,在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);
}

看不懂的可以在评论中回复,笔者会收到邮件通知。

阅读原文

关注我


微信公众号:iOSDevShares
有问必答QQ群:324400294

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值