美文网首页
UITextField输入框字数以及中文字母限制

UITextField输入框字数以及中文字母限制

作者: 蜗牛的马达 | 来源:发表于2019-05-07 22:11 被阅读0次

LQInputLimitTextField.h文件

typedef NS_ENUM(NSInteger, LQInputTextType) {
    ///默认不做输入文本任何限制
    LQInputTextTypeDefault = 0,
    ///只能输入中文,这里仅包含基本汉字20902个,范围是\u4e00-\u9fa5
    LQInputTextTypeZh,
    ///只能输入26个字母,不区分大小写
    LQInputTextTypeAlphabet,
    ///只能输入数字
    LQInputTextTypeDecimalDigit,
    ///只能输入字母和数字
    LQInputTextTypeAlphabetDecimalDigit
};
///用于字数限制
@interface LQInputLimitTextField : UITextField

///最大输入字符长度
@property (nonatomic, assign) NSUInteger maxInputLength;
///最大输入字节数:规则:汉字=2字节,字符=1字节
@property (nonatomic, assign) NSUInteger maxInputByteLength;
///设置输入文本的限制类型
@property (nonatomic, assign) LQInputTextType textType;
///输入文本回调
@property (nonatomic, copy) void (^TextfieldTextChangedBlock)(NSString* text);

@end

LQInputLimitTextField.m文件

#import "LQInputLimitTextField.h"

@implementation LQInputLimitTextField

- (void)setMaxInputLength:(NSUInteger)maxInputLength {
    _maxInputLength = maxInputLength;
    if (maxInputLength > 0) {
        [self addTarget:self action:@selector(p_actionTextFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    }
}
- (void)setMaxInputByteLength:(NSUInteger)maxInputByteLength {
    _maxInputByteLength = maxInputByteLength;
    if (maxInputByteLength > 0) {
        [self addTarget:self action:@selector(p_actionTextFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    }
}
#pragma mark --- actions
- (void)p_actionForInputTextTypeInText:(NSString *)text {
    NSMutableString* strM = [NSMutableString stringWithString:text];
    
    switch (self.textType) {
        case LQInputTextTypeZh:
        {
            NSString* pattern = @"[^\u4e00-\u9fA5]+";//这里只匹配基本汉字,关于汉字的扩展unicode码尚未考虑
            NSRegularExpression* reg = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
            NSArray<NSTextCheckingResult*>* matches = [reg matchesInString:text options:NSMatchingReportProgress range:NSMakeRange(0, strM.length)];
            for (NSTextCheckingResult* one in matches) {
                [strM replaceCharactersInRange:one.range withString:@""];
            }
        }
            break;
        case LQInputTextTypeAlphabet:
        {
            NSMutableCharacterSet* setM = [NSMutableCharacterSet lowercaseLetterCharacterSet];
            [setM formUnionWithCharacterSet:NSCharacterSet.uppercaseLetterCharacterSet];
            NSMutableArray<NSString*>* components = [text componentsSeparatedByCharactersInSet:setM].mutableCopy;
            [components removeObject:@""];
            for (NSString* one in components) {
                [strM replaceOccurrencesOfString:one withString:@"" options:0 range:NSMakeRange(0, strM.length)];
            }
        }
            break;
        case LQInputTextTypeDecimalDigit:
        {
            NSMutableCharacterSet* setM = [NSMutableCharacterSet decimalDigitCharacterSet];
            NSMutableArray<NSString*>* components = [text componentsSeparatedByCharactersInSet:setM].mutableCopy;
            [components removeObject:@""];
            for (NSString* one in components) {
                [strM replaceOccurrencesOfString:one withString:@"" options:0 range:NSMakeRange(0, strM.length)];
            }
        }
            break;
        case LQInputTextTypeAlphabetDecimalDigit:
        {
            NSMutableCharacterSet* setM = [NSMutableCharacterSet lowercaseLetterCharacterSet];
            [setM formUnionWithCharacterSet:NSCharacterSet.uppercaseLetterCharacterSet];
            [setM formUnionWithCharacterSet:NSCharacterSet.decimalDigitCharacterSet];
            NSMutableArray<NSString*>* components = [text componentsSeparatedByCharactersInSet:setM].mutableCopy;
            [components removeObject:@""];
            for (NSString* one in components) {
                [strM replaceOccurrencesOfString:one withString:@"" options:0 range:NSMakeRange(0, strM.length)];
            }
        }
            break;
        default:
            break;
    }
    self.text = strM.copy;
}
- (void)p_actionForTextFieldValueChanged:(UITextField*)textField {
    NSString* originalText = textField.text;
    UITextRange* markedRange = [textField markedTextRange];
    UITextPosition* position = [textField positionFromPosition:markedRange.start offset:0];
    
    if (!position) {//没有高亮部分,则可以对已输入的文字进行字数统计和限制
        
        [self p_actionForInputTextTypeInText:originalText];
        originalText = textField.text;
        
        if (_maxInputLength > 0) {
            if (originalText.length > self.maxInputLength) {
                NSRange validRange = [originalText rangeOfComposedCharacterSequenceAtIndex:self.maxInputLength];
                if (1 == validRange.length) {
                    textField.text = [originalText substringToIndex:self.maxInputLength];
                }else {
                    NSRange range = [originalText rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.maxInputLength)];
                    textField.text = [originalText substringWithRange:range];
                }
            }
        }else {
            NSStringEncoding encGb2312 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            NSUInteger bytelength = [originalText lengthOfBytesUsingEncoding:encGb2312];
            if (bytelength > self.maxInputByteLength) {
                NSData* data = [originalText dataUsingEncoding:encGb2312];
                NSData* subData = nil;
                subData = [data subdataWithRange:NSMakeRange(0, self.maxInputByteLength)];

                NSUInteger minus = 0;
                NSString* correctText = [[NSString alloc] initWithData:subData encoding:encGb2312];
                while (!correctText) {
                    minus++;
                    subData = [data subdataWithRange:NSMakeRange(0, self.maxInputByteLength-minus)];
                    correctText = [[NSString alloc] initWithData:subData encoding:encGb2312];
                }
                textField.text = correctText;
            }
        }
        if (self.TextfieldTextChangedBlock) {
            self.TextfieldTextChangedBlock(textField.text);
        }
    }
}
- (void)dealloc {
   [self removeTarget:self action:@selector(p_actionForTextFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];;
}

@end

相关文章

网友评论

      本文标题:UITextField输入框字数以及中文字母限制

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