美文网首页
UITextField开发相关

UITextField开发相关

作者: geekAppke | 来源:发表于2018-03-19 17:09 被阅读34次
最大长度maxLength

最大长度maxLength

@interface UITextField (BN)
@property (nonatomic, assign) NSUInteger maxLength;
- (NSString *)getValue;

@end
----------------------------------------------------------------
#import "UITextField+BN.h"
#import <objc/runtime.h>

@interface UITextFieldMaxLengthObserver: NSObject
@end

@implementation UITextFieldMaxLengthObserver

- (void)textChange:(UITextField *)textField {
    NSString *destText = textField.text;
    NSUInteger maxLength = textField.maxLength;
    
    // 对中文的特殊处理,shouldChangeCharactersInRangeWithReplacementString 并不响应中文输入法的选择事件
    // 如拼音输入时,拼音字母处于选中状态,此时不判断是否超长
    UITextRange *selectedRange = [textField markedTextRange];
    if (!selectedRange || !selectedRange.start) {
        if (destText.length > maxLength) {
            textField.text = [destText substringToIndex:maxLength];
        }
    }
}

@end

static UITextFieldMaxLengthObserver *observer;

@implementation UITextField (BN)

+ (void)load {
    observer = [[UITextFieldMaxLengthObserver alloc] init];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setMaxLength:(NSUInteger)maxLength {
    objc_setAssociatedObject(self, @selector(maxLength), @(maxLength), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (maxLength) {
        [self addTarget:observer action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    }
}

- (NSUInteger)maxLength {
    NSNumber *number = objc_getAssociatedObject(self, @selector(maxLength));
    return [number integerValue];
}

- (NSString *)getValue {
    return self.text;
}

@end

相关文章

网友评论

      本文标题:UITextField开发相关

      本文链接:https://www.haomeiwen.com/subject/axmpqftx.html