UITextField+ExtentRange.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // UITextField+ExtentRange.m
  3. // DDTG
  4. //
  5. // Created by 翟玉磊 on 16/11/8.
  6. // Copyright © 2016年 翟玉磊. All rights reserved.
  7. //
  8. #import "UITextField+ExtentRange.h"
  9. @implementation UITextField (ExtentRange)
  10. - (NSRange) selectedRange
  11. {
  12. UITextPosition* beginning = self.beginningOfDocument;
  13. UITextRange* selectedRange = self.selectedTextRange;
  14. UITextPosition* selectionStart = selectedRange.start;
  15. UITextPosition* selectionEnd = selectedRange.end;
  16. const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
  17. const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
  18. return NSMakeRange(location, length);
  19. }
  20. - (void) setSelectedRange:(NSRange) range // 备注:UITextField必须为第一响应者才有效
  21. {
  22. UITextPosition* beginning = self.beginningOfDocument;
  23. UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
  24. UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
  25. UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
  26. [self setSelectedTextRange:selectionRange];
  27. }
  28. /**
  29. 修改默认字体颜色
  30. @param color 要修改成的颜色
  31. */
  32. - (void)changePlaceholderColor:(UIColor *)color {
  33. self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName: color}];
  34. }
  35. /**
  36. setup Clean Button Image
  37. @param imageName 图片名字
  38. */
  39. - (void)setupCleanButtonImageName:(NSString *)imageName {
  40. UIButton *cleanButton = [self valueForKey:@"_clearButton"];
  41. [cleanButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
  42. [cleanButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateHighlighted];
  43. }
  44. @end