UITextField 限制输入

UITextField+Expand.h
#import 

typedef void(^LimitBlock)(void);

NS_ASSUME_NONNULL_BEGIN

@interface UITextField (Expand)

@property (nonatomic , copy)LimitBlock limitBlock;

- (void)lengthLimit:(void (^)(void))limit;

@end

NS_ASSUME_NONNULL_END
UITextField+Expand.m
#import "UITextField+Expand.h"
#import 

@implementation UITextField (Expand)

static char limit;

- (void)setLimitBlock:(LimitBlock)limitBlock {
    objc_setAssociatedObject(self, &limit, limitBlock, OBJC_ASSOCIATION_COPY);
}

- (LimitBlock)limitBlock {
    return objc_getAssociatedObject(self, &limit);
}

- (void)lengthLimit:(void (^)(void))limit {
    [self addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.limitBlock = limit;
}

- (void)textFieldEditChanged:(UITextField *)textField {
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
    if (!position){
        if (self.limitBlock) {
            self.limitBlock();
        }
    }
}

@end
[self.nickNameTf lengthLimit:^{
        if (self.nickNameTf.text.length > 8) {
            self.nickNameTf.text = [self.nickNameTf.text substringToIndex:8];
        }
    }];

你可能感兴趣的:(UITextField 限制输入)