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

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,696评论 0 3
  • 开发过程中,我们会收到产品各种需求,比如使用手机号码登录或注册时限制输入字数为11位,那应该怎么实现呢?UITex...
    KnowWhy阅读 362评论 0 0
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,341评论 0 2
  • ## 可重入函数 ### 可重入性的理解 若一个程序或子程序可以安全的被并行执行,则称其为可重入的;即当该子程序正...
    夏至亦韵阅读 707评论 0 0
  • 在眼波流转之间 身体的器官迷茫,迷茫 那该是怎样的方向 是否已蜷缩于古老的藤椅 在苇草与肌肤之间 婆娑微微的痛感 ...
    小白army阅读 290评论 2 4