在项目中,UITextField基本上都要求输入长度限制,通常的做法是监听UITextField
[self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField
{
NSString *toBeString = textField.text;
//获取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
CGFloat maxLength = 8;
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position){
if (toBeString.length > maxLength){
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
if (rangeIndex.length == 1){
textField.text = [toBeString substringToIndex:maxLength];
}
else{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
textField.text = [toBeString substringWithRange:rangeRange];
}
}
}
}
然后在监听的方法里面控制输入长度。但是如果有很多页面都要求UITextField输入限制,每个页面都加监听太麻烦了
所以我们可以提取一个Category
UITextField+Expand.h
#import <UIKit/UIKit.h>
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 <objc/runtime.h>
@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];
}
}];
只要两句代码就可以实现了。