前言:
很多情况下,输入框都是需要按照要求进行输入。例如:密码输入框只能输入纯数字或者是拼音与数字结合的文本等,那么我们在开发的时候就需要做一些输入文本的限制。当然,以下的方法都可以使用正则来实现,找个时间我顺便把正则也给补充上来~
- 只能输入纯数字
在这里以UITextField为例:其实现代码如下:
#define Numbers @"1234567890"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//invertedSet方法是去反字符,把所有的除了Numbers里的字符都找出来(包含去空格功能)
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:Numbers invertedSet];
//利用上述得到的反字符集合分割原有字符串,并且重新拼接起来就得到纯数字字符串
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
// 如果重新拼接起来的字符串和原字符串相同说明没有其他字符
return [string isEqualToString:filtered];
}
- 只能输入纯大小写字母
和以上只能输入纯数字类似,实现起来简单,只需要宏定义
#define LETTER @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LETTER] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
- 大小写字母和数字结合输入
方法类似上面的做法
#define LETTER_NUMBER @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
同样道理,具体能够输入哪些内容如果输入内容能够一一列举的话我们就可以通过define来设置了,实现起来超简单。
限制只能输入中文
在这里用到了观察者(因为其实通过联想/复制输入是不会走shouldChangeCharactersInRange代理方法的,会导致联想输入的中文没法控制,所以需要通过KVO监听 , 不过有时候我一般选择直接关掉联想,世界清静~~)
- (void)viewDidLoad {
[super viewDidLoad];
_myTextField.delegate = self;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:_myTextField];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
//过滤非汉字字符
textField.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];
//截四位汉字
if (textField.text.length >= 4) {
textField.text = [textField.text substringToIndex:4];
}
return NO;
}
- (void)textFiledEditChanged:(id)notification{
UITextRange *selectedRange = _myTextField.markedTextRange;
UITextPosition *position = [_myTextField positionFromPosition:selectedRange.start offset:0];
if (!position) { //// 没有高亮选择的字
//过滤非汉字字符
_myTextField.text = [self filterCharactor:_myTextField.text withRegex:@"[^\u4e00-\u9fa5]"];
if (_myTextField.text.length >= 4) {
_myTextField.text = [_myTextField.text substringToIndex:4];
}
}else { //有高亮文字
//do nothing
}
}
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
NSString *searchText = string;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
return result;
}
- 如果要限制输入字符位数的话可以直接设置,这个实现上有很多种,最简单的就是
- (void)textViewDidChange:(UITextView *)textView{
NSInteger number = [textView.text length];
if (number > 300) {
textView.text = [textView.text substringToIndex:300];
}
}
- 如果输入框是金额类数字,需要限制小数点前小数点后位数可以用下面的分类方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return [NSString limitPayMoneyDot:textField shouldChangeCharactersInRange:range replacementString:string dotPreBits:10 dotAfterBits:2];
}
+ (BOOL) limitPayMoneyDot:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string dotPreBits:(int)dotPreBits dotAfterBits:(int)dotAfterBits
{
static NSString *myDotNumbers = @"0123456789.\n";
static NSString *myNumbers = @"0123456789\n";
/********** 过滤各种情况 **********/
if ([string isEqualToString:@"\n"] || [string isEqualToString:@""])
{ //按下return
return YES;
}
//当设置小数点后位数为0时不能输入小数点
if([string isEqualToString:@"."] && dotAfterBits == 0){
return NO;
}
//首位不能是小数点 | 不能多个小数点 | 不能首位多个0 | 小数点后最后一位不能是0
if(([string isEqualToString:@"."] && textField.text.length == 0) || ([textField.text containsString:@"."] && [string isEqualToString:@"."]) || ([string isEqualToString:@"0"] && [textField.text isEqualToString:@"0"])){
return NO;
}
/********** 开始限制逻辑 **********/
NSCharacterSet *cs;
NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
//不能0.00000, 也就是前面都是0的情况下小数点最后一位不能是0
if (nDotLoc != NSNotFound && range.location == nDotLoc + dotAfterBits ) {
float number = [textField.text floatValue];
if (number == 0 && [string isEqualToString:@"0"]) {
return NO;
}
}
if (NSNotFound == nDotLoc && 0 != range.location)//整数
{
//去空格去数字
cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers] invertedSet];
if ([string isEqualToString:@"."])
{
return YES;
}
//超过整数位数限制
if (textField.text.length >= dotPreBits)
{
return NO;
}
}
else //非整数
{
cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers] invertedSet];
if (textField.text.length >= dotPreBits + dotAfterBits + 1)
{
//超过位数限制
return NO;
}
}
//过滤
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [string isEqualToString:filtered];
if (!basicTest)
{
//输入了非法字符
return NO;
}
if (NSNotFound != nDotLoc && range.location > nDotLoc + dotAfterBits)
{ //超过位数限制
return NO;
}
return YES;
}