1.使用分类判断一个字符是不是字母或者数字(regex为正则表达式,可根据需求更改)
#import "NSString+String.h"
@implementation NSString (String)
-(BOOL)deptNumInputShouldNumberAndString{
if (self.length == 0) {
return NO;
}
NSString *regex = @"^[A-Za-z0-9]+$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
if ([pred evaluateWithObject:self]) {
return YES;
}
return NO;
}
@end
2.在textField代理方法中调用分类方法,如果不是字母和数字,则返回no
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (![string deptNumInputShouldNumberAndString]) {
return NO;
}
return YES;
}
3.监听位数。对代理方法中的string做判断,如果是空(@"")则输入的是X按钮即清除按钮,不能用textfield.text值的长度去判断
-(NSInteger)getCountSum:(NSInteger)countSum{
if ([self isEqual:@""]) {
if (countSum != 0) {
countSum--;
}
}
else{
countSum++;
}
return countSum;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
_sum = [string getCountSum:_sum];
return YES;
}