UITextField+JCTextField.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // UITextField+JCTextField.m
  3. // JCKeyBoard
  4. //
  5. // Created by QB on 16/4/27.
  6. // Copyright © 2016年 JC. All rights reserved.
  7. //
  8. #import "UITextField+JCTextField.h"
  9. /*
  10. * 1.UITextPosition和UITextRange类是符合UITextInput文档,
  11. * 2.UITextPosition代表一个文本容器中的位置
  12. * 3.UITextRange对象封装了开始和结束UITextPosition的对象
  13. */
  14. @implementation UITextField (JCTextField)
  15. ///变换输入框的 输入的字符串
  16. - (void)changTextWithNSString:(NSString *)text {
  17. //UITextPosition对象
  18. //文本开始
  19. UITextPosition *begining = self.beginningOfDocument;
  20. //标记和选定文本
  21. UITextPosition *start = self.selectedTextRange.start;
  22. UITextPosition *end = self.selectedTextRange.end;
  23. //计算文本的范围和位置
  24. NSInteger startIndex = [self offsetFromPosition:begining toPosition:start];
  25. NSInteger endIndex = [self offsetFromPosition:begining toPosition:end];
  26. //获取输入的字符串
  27. NSString *originText = self.text;
  28. //截取字符串---从字符串的开头一直截取到指定的位置,但不包括该位置的字符
  29. NSString *firstPart = [originText substringToIndex:startIndex];
  30. //截取字符串---从指定位置开始(包括指定位置的字符),并包括之后的全部字符
  31. NSString *secondPart = [originText substringFromIndex:endIndex];
  32. // 设置变量
  33. NSInteger offset;
  34. if (![text isEqualToString:@""]) {
  35. offset = text.length;
  36. } else {
  37. if (startIndex == endIndex) {
  38. if (startIndex == 0) {
  39. return;
  40. }
  41. offset = -1;
  42. firstPart = [firstPart substringToIndex:(firstPart.length - 1)];
  43. } else {
  44. offset = 0;
  45. }
  46. }
  47. NSString *newText = [NSString stringWithFormat:@"%@%@%@", firstPart, secondPart, text];
  48. self.text = newText;
  49. UITextPosition *now = [self positionFromPosition:start offset:offset];
  50. UITextRange *range = [self textRangeFromPosition:now toPosition:now];
  51. self.selectedTextRange = range;
  52. }
  53. @end