一. 前言
我們?cè)陧?xiàng)目開(kāi)發(fā)中很經(jīng)常會(huì)碰到各種對(duì)輸入框的限制需求,比如姓名最多只能10字符,密碼最多只能16個(gè)字符,金額最多9位數(shù)且小數(shù)點(diǎn)只能保留兩位小數(shù),且不能包含表情,更有甚者,可能會(huì)要求姓名,中文最多6個(gè)字符,英文最多12個(gè)字符。面對(duì)著各種錯(cuò)綜復(fù)雜輸入限制以及不同種類的第三方鍵盤(pán),處理起來(lái)很經(jīng)常需要寫(xiě)一定量的代碼,且處理邏輯相對(duì)復(fù)雜。基于這樣的情況,于是編寫(xiě)了這樣一個(gè)輸入框攔截器:FJFTextInputIntercepter。
FJFTextInputIntercepter攔截器的作用就類似于你請(qǐng)的家政服務(wù),原本你需要自己來(lái)打掃家里,但是現(xiàn)在你只需把你的需求告訴家政人員,他們會(huì)按照你的需求來(lái)進(jìn)行打掃,最后將打掃結(jié)果告知你。輸入框攔截器就類似這樣的效果,你只需告訴它輸入的限制條件,然后他就會(huì)將依據(jù)你的限制條件進(jìn)行處理,并將處理結(jié)果回調(diào)給你。
這個(gè)輸入框攔截器:FJFTextInputIntercepter使用簡(jiǎn)單,只需設(shè)置限制條件,然后傳入需要限制的輸入框,其他的就交給攔截器進(jìn)行處理。
二.使用介紹
- 使用方法
/**
設(shè)置 需要 攔截的輸入框
@param textInputView 輸入框
*/
- (void)textInputView:(UIView *)textInputView;
/**
設(shè)置 攔截器和攔截的輸入框
@param textInputView 輸入框
@param intercepter 攔截器
*/
+ (void)textInputView:(UIView *)textInputView setInputIntercepter:(FJFTextInputIntercepter *)intercepter;
/**
生成 輸入框 攔截器
@param textInputView 需要限制的輸入框
@param beyoudLimitBlock 超過(guò)限制 回調(diào)
@return 生成 輸入框 攔截器
*/
+ (FJFTextInputIntercepter *)textInputView:(UIView *)textInputView beyoudLimitBlock:(FJFTextInputIntercepterBlock)beyoudLimitBlock;
舉個(gè)例子:
金額輸入限制:最多9位數(shù),最多保留2位小數(shù)。
// 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 = @"請(qǐng)輸入金額(最多9位數(shù),保留2位小數(shù))";
FJFTextInputIntercepter *intercepter = [[FJFTextInputIntercepter alloc] init];
// 最多輸入9位數(shù)
intercepter.maxCharacterNum = 9;
// 保留兩位小數(shù)
intercepter.decimalPlaces = 2;
// 分?jǐn)?shù)類型
intercepter.intercepterNumberType = FJFTextInputIntercepterNumberTypeDecimal;
intercepter.beyoudLimitBlock = ^(FJFTextInputIntercepter *textInputIntercepter, NSString *string) {
NSLog(@"最多只能輸入9位數(shù)字");
};
[intercepter textInputView:_moneyTextFieldView.textField];
}
return _moneyTextFieldView;
}
如上我們可以看到:
我們生成了一個(gè)FJFTextInputIntercepter攔截器實(shí)例,然后給實(shí)例的屬性分別添加限制要求,最后將限制的輸入框傳入攔截器,表示對(duì)此輸入框依據(jù)限制要求進(jìn)行輸入攔截。
- 集成方法:
靜態(tài):手動(dòng)將FJFTextInputIntercepter文件夾拖入到工程中。
動(dòng)態(tài):CocoaPods:pod 'FJFTextInputIntercepter'
github 鏈接
Demo地址: https://github.com/fangjinfeng/FJFTextInputIntercepter
-
效果展示:
FJFTextInputIntercepter.gif
三. 原理分析
1. 原理簡(jiǎn)介
FJFTextInputIntercepter只有一種調(diào)用方法就是:
- 首先生成
攔截器實(shí)例:
FJFTextInputIntercepter *intercepter = [[FJFTextInputIntercepter alloc] init];
- 然后給
攔截器實(shí)例相關(guān)屬性設(shè)置限制要求:
intercepter.maxCharacterNum = 10;
intercepter.emojiAdmitted = NO;
intercepter.doubleBytePerChineseCharacter = NO;
intercepter.beyoudLimitBlock = ^(FJFTextInputIntercepter *textInputIntercepter, NSString *string) {
NSLog(@"最多只能輸入漢字5個(gè)字,英文10個(gè)字母");
};
- 最后設(shè)置
攔截對(duì)象即需要進(jìn)行輸入限制的輸入框:
[intercepter textInputView:_nameTextFieldView.textField];
2. 代碼分析:
屬性分析:
// maxCharacterNum 限制 最大 字符
@property (nonatomic, assign) NSUInteger maxCharacterNum;
// decimalPlaces 小數(shù) 位數(shù)
// (當(dāng)intercepterNumberType 為FJFTextInputIntercepterNumberTypeDecimal 有用)
@property (nonatomic, assign) NSUInteger decimalPlaces;
// beyoudLimitBlock 超過(guò)限制 最大 字符數(shù) 回調(diào)
@property (nonatomic, copy) FJFTextInputIntercepterBlock beyoudLimitBlock;
// emojiAdmitted 是否 允許 輸入 表情
@property (nonatomic, assign, getter=isEmojiAdmitted) BOOL emojiAdmitted;
// intercepterNumberType 數(shù)字 類型
// FJFTextInputIntercepterNumberTypeNone 默認(rèn)
// FJFTextInputIntercepterNumberTypeNumberOnly 只允許 輸入 數(shù)字,emojiAdmitted,decimalPlaces 不起作用
// FJFTextInputIntercepterNumberTypeDecimal 分?jǐn)?shù) emojiAdmitted 不起作用 decimalPlaces 小數(shù) 位數(shù)
@property (nonatomic, assign) FJFTextInputIntercepterNumberType intercepterNumberType;
/**
doubleBytePerChineseCharacter 為 NO
字母、數(shù)字、漢字都是1個(gè)字節(jié) 表情是兩個(gè)字節(jié)
doubleBytePerChineseCharacter 為 YES
不允許 輸入表情 一個(gè)漢字是否代表兩個(gè)字節(jié) default YES
允許 輸入表情 一個(gè)漢字代表3個(gè)字節(jié) 表情 代表 4個(gè)字節(jié)
*/
@property (nonatomic, assign, getter=isDoubleBytePerChineseCharacter) BOOL doubleBytePerChineseCharacter;
屬性功能如注釋所示,攔截器默認(rèn)設(shè)置如下屬性:
_emojiAdmitted = NO;
_maxCharacterNum = UINT_MAX;
_doubleBytePerChineseCharacter = NO;
_intercepterNumberType = FJFTextInputIntercepterNumberTypeNone;
默認(rèn)不允許輸入表情、不限制最大輸入字符數(shù)、漢字和字符同樣一個(gè)字節(jié)、表情兩個(gè)字節(jié)、不設(shè)置數(shù)字類型。
限制邏輯分析:
- A. 調(diào)用公共方法:
#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];
}
}
從代碼中我們可以看出最后都會(huì)走:
+ (void)textInputView:(UIView *)textInputView setInputIntercepter:(FJFTextInputIntercepter *)intercepter
類方法,這里對(duì)輸入框類型進(jìn)行了判斷,并設(shè)置將攔截器和輸入框關(guān)聯(lián)在一起,保證攔截器的生命周期和輸入框一致,同時(shí)注冊(cè)了文本改變的通知。
- 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];
}
}
該函數(shù)主要對(duì)是否為當(dāng)前第一響應(yīng)者和通知名稱是否匹配進(jìn)行判斷,然后調(diào)用輸入框類型對(duì)應(yīng)的通知處理方法。
- 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;
}
通知處理方法內(nèi)部分別獲取當(dāng)前語(yǔ)言類型、和高亮部分,然后調(diào)用輸入文本的處理方法:handleWithInputText和最大輸入字符的截取方法:finalTextAfterProcessingWithInput。
- D. 在
輸入文本的處理方法:handleWithInputText中分別對(duì)只能輸入數(shù)字、輸入分?jǐn)?shù)和是否允許輸入表情進(jìn)行處理.
// 處理 輸入 字符串
- (NSString *)handleWithInputText:(NSString *)inputText {
if (_previousText.length >= inputText.length) {
return inputText;
}
NSString *tmpReplacementString = [inputText substringWithRange:NSMakeRange(_previousText.length, (inputText.length - _previousText.length))];
// 只允許 輸入 數(shù)字
if (self.intercepterNumberType == FJFTextInputIntercepterNumberTypeNumberOnly) {
if ([tmpReplacementString fjf_isCertainStringType:FJFTextInputStringTypeNumber] == NO) {
inputText = _previousText;
}
}
// 輸入 小數(shù)
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函數(shù)中依據(jù)是否為中文輸入法來(lái)分別進(jìn)行處理
// 核心代碼
- (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"]) { // 簡(jiǎn)繁體中文輸入
// 沒(méi)有高亮選擇的字,則對(duì)已輸入的文字進(jìn)行字?jǐn)?shù)統(tǒng)計(jì)和限制
if (!textPosition) {
finalText = [self processingTextWithInput:inputText
maxCharacterNum:maxCharacterNum
isDoubleBytePerChineseCharacter:isDoubleBytePerChineseCharacter];
}
} else { // 中文輸入法以外的直接對(duì)其統(tǒng)計(jì)限制即可,不考慮其他語(yǔ)種情況
finalText = [self processingTextWithInput:inputText
maxCharacterNum:maxCharacterNum
isDoubleBytePerChineseCharacter:isDoubleBytePerChineseCharacter];
}
return finalText;
}
這段代碼里面判斷了是否為簡(jiǎn)繁體中文輸入,如果不是簡(jiǎn)繁體中文輸入,直接調(diào)用processingTextWithInput方法對(duì)已輸入的文字進(jìn)行字?jǐn)?shù)和統(tǒng)計(jì)的限制,如果是簡(jiǎn)繁體中文輸入,判斷是否為高亮選擇的字,如果不是高亮選擇的字,對(duì)已輸入的文字進(jìn)行字?jǐn)?shù)和統(tǒng)計(jì)的限制。
- G.
processingTextWithInput依據(jù)是否一個(gè)漢字對(duì)應(yīng)兩個(gè)字節(jié)來(lái)分別進(jìn)行處理
- (NSString *)processingTextWithInput:(NSString *)inputText
maxCharacterNum:(NSUInteger)maxCharacterNum
isDoubleBytePerChineseCharacter:(BOOL)isDoubleBytePerChineseCharacter {
NSString *processingText = nil;
if (isDoubleBytePerChineseCharacter) { //如果一個(gè)漢字是雙字節(jié)
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;
}
該函數(shù)判斷如果一個(gè)漢字是雙字節(jié),就調(diào)用doubleBytePerChineseCharacterSubString依據(jù)是否允許輸入表情,調(diào)用不同的編碼方式進(jìn)行處理。如果一個(gè)漢字是一個(gè)字節(jié),直接進(jìn)行最大字符截取。
四. 總結(jié)
綜上所述就是FJFTextInputIntercepter這個(gè)輸入框的一個(gè)設(shè)計(jì)思路,核心代碼量差不多400行左右,能應(yīng)對(duì)大部分的輸入框要求`,使用簡(jiǎn)單。

如果你覺(jué)得你覺(jué)得這思路或是代碼有什么問(wèn)題,歡迎留言大家討論下!如果覺(jué)得不錯(cuò),麻煩給個(gè)喜歡或star,謝謝!
