iOS具有过滤功能的输入框

功能列表

1.无输入限制;
2.只能输入数字和字母;
3.只能输入字母;
4.只能输入数字;
5.输入的字母自动转换为大写(解决插入文本后光标跑到最后的问题);
6.过滤黏贴数据(解决iOS粘贴自动添加空格的问题)

实现原理

1.头文件

//
//  CPCheckTextField.h
//  CPTools
//
//  Created by wangzhangchuan on 2018/4/12.
//  Copyright © 2018年 Captain. All rights reserved.
//

#import "CPView.h"

typedef NS_ENUM(NSInteger, CPTextFiledDataType) {
    CPTextFiledDataTypeAll,             //  无限制
    CPTextFiledDataTypeAlphabet,        //  字母
    CPTextFiledDataTypeNum,             //  数字
    CPTextFiledDataTypeNumDecimal,      //  浮点数
    CPTextFiledDataTypeNumAlphabet,     //  数字字母
    CPTextFiledDataTypeOther            //  预留
};

@protocol CPCheckTextFieldDelegate<NSObject>

@optional
- (void)cp_textFieldDidBeginEditing:(UITextField *)textField;
- (void)cp_textFieldDidEndEditing:(UITextField *)textField;

@end

@interface CPCheckTextField : CPView<UITextFieldDelegate>

@property (nonatomic, weak) id <CPCheckTextFieldDelegate> delegate;

//  文本最大长度
@property (nonatomic, assign) NSInteger maxContentLength;

//键盘类型
@property (nonatomic, assign) UIKeyboardType keyboardType;

//是否密码输入模式
@property (nonatomic, assign) BOOL secureTextEntry;

//错误信息提示内容
@property (nonatomic, copy) NSString *errorMsg;

//自动大写模式
@property (nonatomic, assign) UITextAutocapitalizationType autocapitalizationType;

//数据类型
@property (nonatomic, assign) CPTextFiledDataType dataType;

//是否需要大写
@property (nonatomic, assign) BOOL isUpercaseString;

@end

2.实现

#pragma mark - textfield delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    //  总的字符串不能超过 maxContentLength
    if (textField.text.length + string.length > self.maxContentLength) {
        return NO;
    }
    
    NSMutableCharacterSet *cs = [NSMutableCharacterSet characterSetWithCharactersInString:@""];
    switch (self.dataType) {
        case CPTextFiledDataTypeAlphabet:
        {
            [cs addCharactersInString:ALPHABET];
        }
            break;
        case CPTextFiledDataTypeNum:
        {
            [cs formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
        }
            break;
        case CPTextFiledDataTypeNumDecimal:
        {
            [cs formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
            
            if (![textField.text containsString:@"."]) {
                [cs addCharactersInString:@"."];
            }
        }
            break;
        case CPTextFiledDataTypeNumAlphabet:
        {
            [cs addCharactersInString:ALPHABET];
            [cs formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
        }
            break;
            
        default:
            break;
    }

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:[cs invertedSet]] componentsJoinedByString:@""];
    
    if ([filtered isEqualToString:string] == NO) {
        
        // 处理粘贴自动添加的前/后空格
        NSMutableString *tempStr = [[NSMutableString alloc] initWithString:string];
        if ([tempStr hasPrefix:@" "]) {
            [tempStr deleteCharactersInRange:NSMakeRange(0, 1)];
        }
        
        if ([tempStr hasSuffix:@" "]) {
            [tempStr deleteCharactersInRange:NSMakeRange(tempStr.length - 1, 1)];
        }
        
        BOOL valied = [filtered isEqualToString:tempStr];
        if (valied == YES) {
            // 自动转为大写
            if (self.isUpercaseString) {
                return [self cp_upercaseSting:range replacementString:tempStr];
            }
                
        } else {
            return NO;
        }

    } else {
        
        // 自动转为大写
        if (self.isUpercaseString) {
            return [self cp_upercaseSting:range replacementString:string];
        }
        
        return YES;
    }

    return YES;
}


/**
 将字母转换为大写

 @param range 插入位置
 @param string 要处理的字符串
 @return YES:使用原字符  NO:使用处理过的字符
 */
- (BOOL)cp_upercaseSting:(NSRange )range replacementString:(NSString *)string {
    
    NSMutableString *tempStr = textField.text.mutableCopy;
    [tempStr insertString:string atIndex:range.location];
    textField.text = [tempStr uppercaseString];
    
    //  光标指定到指定位置
    UITextPosition *starP = [textField positionFromPosition:textField.beginningOfDocument offset:range.location + 1];
    UITextPosition *endP  = [textField positionFromPosition:textField.beginningOfDocument offset:range.location + 1];
    UITextRange *p        = [textField textRangeFromPosition:starP toPosition:endP];
    
    [textField setSelectedTextRange:p];
    
    return NO;
}

代码 Git地址

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 不知不觉,岁寒输入法的更新历史已经可以列出这么一长串来了。从中可以看出,岁寒的发展过程也是一个不断试错的过程,其中...
    临岁之寒阅读 34,343评论 1 6
  • 好久不见!我是美少女壮士。 天气真热啊,最近我都缩在家里,看一部教人谈恋爱的浪漫动画,好清新,好消暑,好解闷…… ...
    Sir电影阅读 1,587评论 2 22
  • 为什么要对你掉眼泪 你难道不明白为了爱 好春才来 春花正开 你怎舍得说再会 望穿秋水 情深如海
    想讲道理的法玛阅读 144评论 0 1
  • STEAM教育:STEAM的原身是STEM理念,即科学(Science)、技术(Technology)、工程(En...
    聆听者JYZ阅读 476评论 0 0
  • 遇见重大疾病患者该有什么反应? 你会有什么反应? 今天在捷运站附近看见了身体无法随己控制的人(帕金森氏症最严重的时...
    Rivoun阅读 322评论 7 4