SPSBTextField.m 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // SPSBTextField.m
  3. // 我的社保
  4. //
  5. // Created by shanp on 2021/4/21.
  6. //
  7. #import "SPSBTextField.h"
  8. #import <JXHMacro.h>
  9. #import <NSObject+JXHNotification.h>
  10. @implementation SPSBTextField
  11. - (instancetype)init {
  12. self = [super init];
  13. if (!self) return nil;
  14. @weakify(self)
  15. [self addNotificationName:UITextFieldTextDidChangeNotification block:^(id _Nullable object, NSDictionary * _Nullable userInfo) {
  16. @strongify(self)
  17. [self textFieldDidChange:object];
  18. }];
  19. return self;
  20. }
  21. - (void)textFieldDidChange:(id)sender {
  22. if (sender != self || _spsb_maxCount == 0) return;
  23. UITextField *textField = sender;
  24. NSString *toBeString = textField.text;
  25. UITextRange *selectedRange = [textField markedTextRange];
  26. // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
  27. if (!selectedRange) {
  28. if (toBeString.length > _spsb_maxCount) {
  29. textField.text = [toBeString substringToIndex:_spsb_maxCount];
  30. }
  31. }
  32. if (_spsb_afterJudge) {
  33. _spsb_afterJudge(self);
  34. }
  35. }
  36. - (void)textDidChange {
  37. [self textFieldDidChange:self];
  38. }
  39. - (void)dealloc {
  40. [self removeNotificationName:UITextFieldTextDidChangeNotification];
  41. }
  42. @end