iOS UITextField 限制输入

热门标签

特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

通常情况下如果要限制UITextField的输入长度或输入类型要么在回调方法判断

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
}

要么在监听里面判断

[self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textFieldDidChange:(UITextField *)textField
{
}

但是如果很多页面的TextField控件需要验证这样写就很麻烦,为了不重复造轮子。写了一个Category。只实现了输入长度限制,输入数字,输入字母,如果不能满足需求可自行扩展。

#import <UIKit/UIKit.h>

typedef void(^TextLengthBlock)(NSInteger length);
typedef void(^IsTextFieldTypeBlock)(BOOL filedType);

typedef NS_ENUM(NSInteger,DTextFieldType) {
    DTextFieldStringTypeNone = 0,            // 不限制
    DTextFieldStringTypeNumber = 1,         // 数字
    DTextFieldStringTypeLetter = 2         // 字母
};

NS_ASSUME_NONNULL_BEGIN

@interface UITextField (Limit)

/**允许输入最大字符长度*/
@property (assign, nonatomic) NSInteger maxLength;
/**输入类型*/
@property (assign, nonatomic) NSInteger textFieldType;
/**输入长度回调(返回输入的字符长度)*/
@property (nonatomic , copy) TextLengthBlock lengthBlock;
/**输入限制类型的回调(判断是否是想要的输入类型,外部提示用)*/
@property (nonatomic , copy) IsTextFieldTypeBlock isTextFieldTypeBlock;


@end

NS_ASSUME_NONNULL_END

#import "UITextField+Limit.h"
#import <objc/runtime.h>

#define kDNUMBERS     @"0123456789\n"
#define kDLETTER     @"abcdefghijklmnopqresuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

static NSString * const DMaxLengthKey = @"DMaxLengthKey";
static NSString * const DTextLengthBlockKey = @"DTextLengthKey";
static NSString * const DTextFieldTypeKey = @"DTextFieldTypeKey";
static NSString * const DIsTextFieldTypeKey = @"DIsTextFieldTypeKey";

@implementation UITextField (Limit)

- (void)setMaxLength:(NSInteger)maxLength{
    objc_setAssociatedObject(self, &DMaxLengthKey, @(maxLength), OBJC_ASSOCIATION_ASSIGN);
    
    [self addTarget:self
             action:@selector(textFieldTextChanged:)
   forControlEvents:UIControlEventEditingChanged];
}
- (NSInteger)maxLength{
    return   [objc_getAssociatedObject(self, &DMaxLengthKey) integerValue];
}

- (void)setLengthBlock:(TextLengthBlock)lengthBlock{
    objc_setAssociatedObject(self, &DTextLengthBlockKey, lengthBlock, OBJC_ASSOCIATION_COPY);
    
    [self addTarget:self
             action:@selector(textFieldTextChanged:)
   forControlEvents:UIControlEventEditingChanged];
}
- (TextLengthBlock)lengthBlock{
    return objc_getAssociatedObject(self, &DTextLengthBlockKey);
}

- (void)setTextFieldType:(NSInteger)textFieldType{
    objc_setAssociatedObject(self, &DTextFieldTypeKey,  @(textFieldType), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)textFieldType{
    return [objc_getAssociatedObject(self, &DTextFieldTypeKey) integerValue];
}

- (void)setIsTextFieldTypeBlock:(IsTextFieldTypeBlock)isTextFieldTypeBlock{
    objc_setAssociatedObject(self, &DIsTextFieldTypeKey, isTextFieldTypeBlock, OBJC_ASSOCIATION_COPY);
}
- (IsTextFieldTypeBlock)isTextFieldTypeBlock{
    return objc_getAssociatedObject(self, &DIsTextFieldTypeKey);
}

- (void)lengthLimitBlock:(UITextField *)textField
{
    if (self.lengthBlock) {
        self.lengthBlock(textField.text.length);
    }
}

- (void)textFieldTextChanged:(UITextField *)textField
{
   
    switch (self.textFieldType) {
        case DTextFieldStringTypeNone:
        {
            [self textFieldStringTypeNumber:textField];
        }
            break;
        case DTextFieldStringTypeNumber:
        {
            [self textFieldStringTypeNumber:textField];
        }
            break;
        case DTextFieldStringTypeLetter:
        {
            [self textFieldStringTypeLetter:textField];
        }
            break;
            
        default:
            break;
    }
    
   [self lengthLimitBlock:textField];
}


/**
 获取TextField输入范围
 @param textField textField
 @return 范围
 */
- (NSRange)getTextFieldRange:(UITextField *)textField
{
    NSInteger adaptedLength = textField.maxLength > 0? MIN(textField.text.length, textField.maxLength) : MIN(textField.text.length, MAXFLOAT);
    NSRange range = NSMakeRange(0, adaptedLength);
    
    return range;
}


/**
 输入类型验证

 @param aStr 输入字符串
 @param format 验证格式
 @return BOOL
 */
- (BOOL)inputTypeVerification:(NSString *)aStr format:(NSString *)format{
    NSCharacterSet* filterCS = [[NSCharacterSet characterSetWithCharactersInString:format] invertedSet];
    NSString *filterString = [[aStr componentsSeparatedByCharactersInSet:filterCS] componentsJoinedByString:@""];
    
    return [aStr isEqualToString:filterString];
}


/**
 无限制(可以输入任何类型)
 @param textField textField
 */
- (void)textFieldStringTypeNone:(UITextField *)textField
{
    textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
}

/**
 只能输入数字
 @param textField textField
 */
- (void)textFieldStringTypeNumber:(UITextField *)textField
{
    BOOL flag = [self inputTypeVerification:textField.text format:kDNUMBERS];
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    }
    else{
        textField.text = @"";
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}

/**
 只能输入字母
 @param textField textField
 */
- (void)textFieldStringTypeLetter:(UITextField *)textField
{
    BOOL flag = [self inputTypeVerification:textField.text format:kDLETTER];;
    if (flag){
        textField.text = [textField.text substringWithRange:[self getTextFieldRange:textField]];
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(YES);
        }
    }
    else{
        textField.text = @"";
        if (self.isTextFieldTypeBlock) {
            self.isTextFieldTypeBlock(NO);
        }
    }
}

@end

使用

self.textField1.textFieldType = DTextFieldStringTypeNumber;
    self.textField1.maxLength = 11;
    
    self.textField1.lengthBlock = ^(NSInteger length) {
        NSLog(@"长度--%zd",length);
    };
    self.textField1.isTextFieldTypeBlock = ^(BOOL filedType) {
        if (!filedType) {
            NSLog(@"请输入正确的类型");
        }
    };

Demo

 

标签:

未经允许不得转载:作者:SheaYang, 转载或复制请以 超链接形式 并注明出处 技术Dog|博客
原文地址:《iOS UITextField 限制输入》 发布于2019-12-04

分享到:
赞(0)

评论 抢沙发

4 + 5 =


iOS UITextField 限制输入

长按图片转发给朋友

Vieu4.0主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录