iOS 输入框拦截器:FJFTextInputIntercepter

一. 前言

我们在项目开发中很经常会碰到各种对输入框的限制需求,比如姓名最多只能10字符密码最多只能16个字符金额最多9位数小数点只能保留两位小数,且不能包含表情,更有甚者,可能会要求姓名中文最多6个字符英文最多12个字符。面对着各种错综复杂输入限制以及不同种类第三方键盘,处理起来很经常需要写一定量的代码,且处理逻辑相对复杂。基于这样的情况,于是编写了这样一个输入框拦截器:FJFTextInputIntercepter

FJFTextInputIntercepter拦截器的作用就类似于你请的家政服务,原本你需要自己来打扫家里,但是现在你只需把你的需求告诉家政人员,他们会按照你的需求来进行打扫,最后将打扫结果告知你。输入框拦截器就类似这样的效果,你只需告诉它输入的限制条件,然后他就会将依据你的限制条件进行处理,并将处理结果回调给你。

这个输入框拦截器:FJFTextInputIntercepter使用简单,只需设置限制条件,然后传入需要限制的输入框,其他的就交给拦截器进行处理。

二.使用介绍

  • 使用方法
/**
 设置 需要 拦截的输入框

 @param textInputView 输入框
 */
- (void)textInputView:(UIView *)textInputView;


/**
 设置 拦截器和拦截的输入框

 @param textInputView 输入框
 @param intercepter 拦截器
 */
+ (void)textInputView:(UIView *)textInputView setInputIntercepter:(FJFTextInputIntercepter *)intercepter;

/**
 生成 输入框 拦截器

 @param textInputView 需要限制的输入框
 @param beyoudLimitBlock 超过限制 回调
 @return 生成 输入框 拦截器
 */
+ (FJFTextInputIntercepter *)textInputView:(UIView *)textInputView beyoudLimitBlock:(FJFTextInputIntercepterBlock)beyoudLimitBlock;

举个例子:
金额输入限制:最多9位数,最多保留2位小数。

// moneyTextFieldView
- (FJTextFieldView *)moneyTextFieldView {
    if (!_moneyTextFieldView) {
        _moneyTextFieldView = [[FJTextFieldView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.cardTextFieldView.frame) + 20, [UIScreen mainScreen].bounds.size.width - 80 - 20, 44)];
        _moneyTextFieldView.tipLabel.text = @"金额:";
        _moneyTextFieldView.textField.placeholder = @"请输入金额(最多9位数,保留2位小数)";
        FJFTextInputIntercepter *intercepter = [[FJFTextInputIntercepter alloc] init];
        // 最多输入9位数
        intercepter.maxCharacterNum = 9;
        // 保留两位小数
        intercepter.decimalPlaces = 2;
        // 分数类型
        intercepter.intercepterNumberType = FJFTextInputIntercepterNumberTypeDecimal;
        intercepter.beyoudLimitBlock = ^(FJFTextInputIntercepter *textInputIntercepter, NSString *string) {
            NSLog(@"最多只能输入9位数字");
        };
        [intercepter textInputView:_moneyTextFieldView.textField];
    }
    return  _moneyTextFieldView;
}

如上我们可以看到:

我们生成了一个FJFTextInputIntercepter拦截器实例,然后给实例的属性分别添加限制要求,最后将限制的输入框传入拦截器,表示对此输入框依据限制要求进行输入拦截

  • 集成方法:
静态:手动将FJFTextInputIntercepter文件夹拖入到工程中。
动态:CocoaPods:pod 'FJFTextInputIntercepter'
  • github 链接

Demo地址: https://github.com/fangjinfeng/FJFTextInputIntercepter

  • 效果展示:
    FJFTextInputIntercepter.gif

三. 原理分析

1. 原理简介

FJFTextInputIntercepter只有一种调用方法就是:

  • 首先生成拦截器实例:
FJFTextInputIntercepter *intercepter = [[FJFTextInputIntercepter alloc] init];
  • 然后给拦截器实例相关属性设置限制要求:
intercepter.maxCharacterNum = 10;
intercepter.emojiAdmitted = NO;
intercepter.doubleBytePerChineseCharacter = NO;
intercepter.beyoudLimitBlock = ^(FJFTextInputIntercepter *textInputIntercepter, NSString *string) {
    NSLog(@"最多只能输入汉字5个字,英文10个字母");
 };
  • 最后设置拦截对象即需要进行输入限制输入框:
[intercepter textInputView:_nameTextFieldView.textField];

2. 代码分析:

属性分析:

// maxCharacterNum 限制 最大 字符
@property (nonatomic, assign) NSUInteger maxCharacterNum;

// decimalPlaces 小数 位数
// (当intercepterNumberType 为FJFTextInputIntercepterNumberTypeDecimal 有用)
@property (nonatomic, assign) NSUInteger decimalPlaces;

// beyoudLimitBlock 超过限制 最大 字符数 回调
@property (nonatomic, copy) FJFTextInputIntercepterBlock beyoudLimitBlock;

// emojiAdmitted 是否 允许 输入 表情
@property (nonatomic, assign, getter=isEmojiAdmitted)   BOOL emojiAdmitted;

// intercepterNumberType 数字 类型
// FJFTextInputIntercepterNumberTypeNone 默认
// FJFTextInputIntercepterNumberTypeNumberOnly 只允许 输入 数字,emojiAdmitted,decimalPlaces 不起作用
// FJFTextInputIntercepterNumberTypeDecimal 分数 emojiAdmitted 不起作用 decimalPlaces 小数 位数
@property (nonatomic, assign) FJFTextInputIntercepterNumberType  intercepterNumberType;

/**
  doubleBytePerChineseCharacter 为 NO
 字母、数字、汉字都是1个字节 表情是两个字节
 doubleBytePerChineseCharacter 为 YES
 不允许 输入表情 一个汉字是否代表两个字节 default YES
 允许 输入表情 一个汉字代表3个字节 表情 代表 4个字节
 */
@property (nonatomic, assign, getter=isDoubleBytePerChineseCharacter) BOOL doubleBytePerChineseCharacter;

属性功能注释所示,拦截器默认设置如下属性:

 _emojiAdmitted = NO;
_maxCharacterNum = UINT_MAX;
_doubleBytePerChineseCharacter = NO;
_intercepterNumberType = FJFTextInputIntercepterNumberTypeNone;

默认不允许输入表情不限制最大输入字符数汉字字符同样一个字节表情两个字节不设置数字类型

限制逻辑分析:

  • A. 调用公共方法:
#pragma mark -------------------------- Public  Methods

- (void)textInputView:(UIView *)textInputView {
    [FJFTextInputIntercepter textInputView:textInputView setInputIntercepter:self];
}


+ (FJFTextInputIntercepter *)textInputView:(UIView *)textInputView beyoudLimitBlock:(FJFTextInputIntercepterBlock)beyoudLimitBlock {
    FJFTextInputIntercepter *tmpInputIntercepter = [[FJFTextInputIntercepter alloc] init];
    tmpInputIntercepter.beyoudLimitBlock = [beyoudLimitBlock copy];
    [self textInputView:textInputView setInputIntercepter:tmpInputIntercepter];
    return tmpInputIntercepter;
    
}


+ (void)textInputView:(UIView *)textInputView setInputIntercepter:(FJFTextInputIntercepter *)intercepter {
    
    if ([textInputView isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)textInputView;
       
        textField.yb_textInputIntercepter = intercepter;
        [[NSNotificationCenter defaultCenter] addObserver:intercepter
                                                 selector:@selector(textInputDidChangeWithNotification:)
                                                     name:UITextFieldTextDidChangeNotification
                                                   object:textInputView];
        
    } else if ([textInputView isKindOfClass:[UITextView class]]) {
        UITextView *textView = (UITextView *)textInputView;
        textView.yb_textInputIntercepter = intercepter;
        [[NSNotificationCenter defaultCenter] addObserver:intercepter
                                                 selector:@selector(textInputDidChangeWithNotification:)
                                                     name:UITextViewTextDidChangeNotification
                                                   object:textInputView];
    }
}

从代码中我们可以看出最后都会走:

+ (void)textInputView:(UIView *)textInputView setInputIntercepter:(FJFTextInputIntercepter *)intercepter

类方法,这里对输入框类型进行了判断,并设置将拦截器输入框关联在一起,保证拦截器生命周期输入框一致,同时注册文本改变通知

  • B. 文本改变通知:
#pragma mark -------------------------- Noti  Methods
- (void)textInputDidChangeWithNotification:(NSNotification *)noti {
    if (![((UIView *)noti.object) isFirstResponder]) {
        return;
    }
    
    BOOL textFieldTextDidChange = [noti.name isEqualToString:UITextFieldTextDidChangeNotification] &&
    [noti.object isKindOfClass:[UITextField class]];
    BOOL textViewTextDidChange = [noti.name isEqualToString:UITextViewTextDidChangeNotification] &&
    [noti.object isKindOfClass:[UITextView class]];
    if (!textFieldTextDidChange && !textViewTextDidChange) {
        return;
    }
    
    if ([noti.name isEqualToString:UITextFieldTextDidChangeNotification]) {
        [self textFieldTextDidChangeWithNotification:noti];
    } else if ([noti.name isEqualToString:UITextViewTextDidChangeNotification]) {
        [self textViewTextDidChangeWithNotification:noti];
    }
}

该函数主要对是否为当前第一响应者通知名称是否匹配进行判断,然后调用输入框类型对应的通知处理方法

  • C. 输入框类型通知处理方法:
#pragma mark -------------------------- Private  Methods

- (void)textFieldTextDidChangeWithNotification:(NSNotification *)noti {
    
    UITextField *textField = (UITextField *)noti.object;
    NSString *inputText = textField.text;
    NSString *primaryLanguage = [textField.textInputMode primaryLanguage];
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *textPosition = [textField positionFromPosition:selectedRange.start
                                                            offset:0];
    
    inputText = [self handleWithInputText:inputText];

    NSString *finalText = [self finalTextAfterProcessingWithInput:inputText
                                                  maxCharacterNum:self.maxCharacterNum
                                                  primaryLanguage:primaryLanguage
                                                     textPosition:textPosition
                                  isDoubleBytePerChineseCharacter:self.isDoubleBytePerChineseCharacter];
    if (finalText.length > 0) {
        textField.text = finalText;
    }
    else if(self.intercepterNumberType == FJFTextInputIntercepterNumberTypeNumberOnly ||
            self.intercepterNumberType == FJFTextInputIntercepterNumberTypeDecimal ||
            self.isEmojiAdmitted == NO){
        textField.text = inputText;
    }
     _previousText = textField.text;
}

- (void)textViewTextDidChangeWithNotification:(NSNotification *)noti {
    
    UITextView *textView = (UITextView *)noti.object;
    NSString *inputText = textView.text;
    NSString *primaryLanguage = [textView.textInputMode primaryLanguage];
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *textPosition = [textView positionFromPosition:selectedRange.start
                                                           offset:0];
    
    inputText = [self handleWithInputText:inputText];
    
    NSString *finalText = [self finalTextAfterProcessingWithInput:inputText
                                                  maxCharacterNum:self.maxCharacterNum
                                                  primaryLanguage:primaryLanguage
                                                     textPosition:textPosition
                                  isDoubleBytePerChineseCharacter:self.isDoubleBytePerChineseCharacter];
    
    if (finalText.length > 0) {
        textView.text = finalText;
    }

    _previousText = textView.text;
}

通知处理方法内部分别获取当前语言类型、和高亮部分,然后调用输入文本的处理方法:handleWithInputText最大输入字符的截取方法:finalTextAfterProcessingWithInput

  • D. 在输入文本的处理方法:handleWithInputText中分别对只能输入数字输入分数是否允许输入表情进行处理.
// 处理 输入 字符串
- (NSString *)handleWithInputText:(NSString *)inputText {
    if (_previousText.length >= inputText.length) {
        return inputText;
    }
    
    NSString *tmpReplacementString = [inputText substringWithRange:NSMakeRange(_previousText.length, (inputText.length - _previousText.length))];
    // 只允许 输入 数字
    if (self.intercepterNumberType == FJFTextInputIntercepterNumberTypeNumberOnly) {
        if ([tmpReplacementString fjf_isCertainStringType:FJFTextInputStringTypeNumber] == NO) {
            inputText = _previousText;
        }
    }
    // 输入 小数
    else if(self.intercepterNumberType == FJFTextInputIntercepterNumberTypeDecimal){
        NSRange tmpRange = NSMakeRange(_previousText.length, 0);
        BOOL isCorrect = [self inputText:_previousText shouldChangeCharactersInRange:tmpRange replacementString:tmpReplacementString];
        if (isCorrect == YES) {
            if (inputText.length == self.maxCharacterNum && [tmpReplacementString isEqualToString:@"."]) {
                 inputText = _previousText;
            }
        }
        else {
            inputText = _previousText;
        }
    }
    // 不允许 输入 表情
    else if (!self.isEmojiAdmitted && [tmpReplacementString fjf_isSpecialLetter]) {
        inputText =  _previousText;
    }
    
    return inputText;
}
  • F. 在finalTextAfterProcessingWithInput函数中依据是否为中文输入法来分别进行处理
// 核心代码
- (NSString *)finalTextAfterProcessingWithInput:(NSString *)inputText
                                maxCharacterNum:(NSUInteger)maxCharacterNum
                                primaryLanguage:(NSString *)primaryLanguage
                                   textPosition:(UITextPosition *)textPosition
                isDoubleBytePerChineseCharacter:(BOOL)isDoubleBytePerChineseCharacter {
    
   

    NSString *finalText = nil;
    if ([primaryLanguage isEqualToString:@"zh-Hans"] ||
        [primaryLanguage isEqualToString:@"zh-Hant"]) { // 简繁体中文输入
        // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
        if (!textPosition) {
            finalText = [self processingTextWithInput:inputText
                                      maxCharacterNum:maxCharacterNum
                      isDoubleBytePerChineseCharacter:isDoubleBytePerChineseCharacter];
        }
        
    } else { // 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
        finalText = [self processingTextWithInput:inputText
                                  maxCharacterNum:maxCharacterNum
                  isDoubleBytePerChineseCharacter:isDoubleBytePerChineseCharacter];
    }
    
    return finalText;
}

这段代码里面判断了是否为简繁体中文输入,如果不是简繁体中文输入,直接调用processingTextWithInput方法已输入的文字进行字数统计的限制,如果是简繁体中文输入,判断是否为高亮选择的字,如果不是高亮选择的字,对已输入的文字进行字数统计的限制

  • G. processingTextWithInput 依据是否一个汉字对应两个字节来分别进行处理
- (NSString *)processingTextWithInput:(NSString *)inputText
                      maxCharacterNum:(NSUInteger)maxCharacterNum
      isDoubleBytePerChineseCharacter:(BOOL)isDoubleBytePerChineseCharacter {
    
    NSString *processingText = nil;
    
    if (isDoubleBytePerChineseCharacter) { //如果一个汉字是双字节
        processingText = [self doubleBytePerChineseCharacterSubString:inputText
                                                      maxCharacterNum:maxCharacterNum];
    } else {
        if (inputText.length > maxCharacterNum) {
            NSRange rangeIndex = [inputText rangeOfComposedCharacterSequenceAtIndex:maxCharacterNum];
            if (rangeIndex.length == 1) {
                processingText = [inputText substringToIndex:maxCharacterNum];
            } else {
                NSRange rangeRange = [inputText rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxCharacterNum)];
                processingText = [inputText substringWithRange:rangeRange];
            }
            if (self.beyoudLimitBlock) {
                self.beyoudLimitBlock(self, processingText);
            }
        }
    }
    return processingText;
}

该函数判断如果一个汉字双字节,就调用doubleBytePerChineseCharacterSubString依据是否允许输入表情,调用不同的编码方式进行处理。如果一个汉字是一个字节,直接进行最大字符截取

四. 总结

综上所述就是FJFTextInputIntercepter这个输入框的一个设计思路核心代码量差不多400行左右,能应对大部分的输入框要求`,使用简单。

image.png

如果你觉得你觉得这思路或是代码有什么问题,欢迎留言大家讨论下!如果觉得不错,麻烦给个喜欢或star,谢谢!

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