TextField的字数限制

569 阅读1分钟

思路:给textfield添加扩展,在扩展.m实现文件里添加属性,用通知的方法来调用字数限制判断,可以判断汉字。废话不多说,代码比较简单,就直接贴出来了

#声明文件

@interface UITextField (limitTextLength)

@property (nonatomic, assign) NSInteger textMax;

- (void)addNotification;

@end

#实现文件

#import "UITextField+limitTextLength.h"

@implementation UITextField (limitTextLength)

static void *textMaxKey = &textMaxKey;

- (NSInteger)textMax {
    
    return [objc_getAssociatedObject(self, &textMaxKey) integerValue];
}

- (void)setTextMax:(NSInteger)textMax {
    
    NSString * max = [NSString stringWithFormat:@"%ld",(long)textMax];
    objc_setAssociatedObject(self, &textMaxKey,max,OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)addNotification {
    
    [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    NSInteger kMaxLength = self.textMax;
    
    NSString *toBeString = textField.text;
    
    NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前
    
    if ([lang isEqualToString:@"zh-Hans"]) {   //中文输入
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮文字
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        //若无高亮选择
        if (!position) {
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        }
    }else {//其他语言
        if (toBeString.length > kMaxLength) {
            textField.text = [toBeString substringToIndex:kMaxLength];
        }
    }
}


@end

#使用方法

导入扩展文件,给需要限制字数的textfield最大字数赋值和添加通知即可

self.confirmPWD.textMax = 20;

[self.confirmPWD addNotification];