在iOS开发中,一些登录界面的手机号、密码或者验证码这些输入框会要求对输入字符数量进行限制。
通常情况下我们会使用注册通知的方法,来监听文本框字符的变化。
// 增加限制位数的通知
- (void)addLimitLengthObserver
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitLengthEvent) name:UITextFieldTextDidChangeNotification object:nil];
}
// 限制输入的位数
- (void)limitLengthEvent
{
if ([textField.text length] > 11) {
textField.text = [textField.text substringToIndex:11];
}
}
一句话搞定
但是如果是类似于填写批量表单的话,就比较麻烦了。
我这里整理了一个方法,一句代码,搞定所有的输入字符限制
Step1:导入pod
pod 'BearSkill'
Step2:导入头文件
#import "UITextField+BearLimitLength.h"
Step3: 使用
textField.limitLength = [NSNumber numberWithInt:11];
这样就OK了,欢迎fork我的BearSkill,里面会包含很多搭建项目中常用的方法整理,https://github.com/BearRan/BearSkill