美文网首页
UITextField

UITextField

作者: 阿龍飛 | 来源:发表于2016-09-26 11:14 被阅读15次

如何更好地限制一个UITextField的输入长度http://www.jianshu.com/p/7a69f15c0268

/**
 *  关闭键盘
 */
- (void)closeKeyboard;

#pragma mark - 关闭键盘
- (void)closeKeyboard {
    //添加手势关闭键盘
    UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    gesture.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:gesture];
}
- (void)closeKeyboard:(UITapGestureRecognizer*)sender {
    [self.view endEditing:YES];
}
[_phoneText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_phoneText addTarget:self action:@selector(textFieldEditingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];

#pragma mark - UITextFieldDelegate 输入只能是数字

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [ToolsClassManager validateNumber:string];
}

#pragma mark - UIControlEventEditingChanged 限制长度

-(void)textFieldDidChange:(UITextField *)textField{
    if (textField == self.phoneText) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}

#pragma mark - UIControlEventEditingDidEnd 正则判断手机号码地址格式

- (void)textFieldEditingDidEnd:(UITextField *)textField {
    if (![ToolsClassManager isMobileNumber:textField.text]) {
        [ZCLUtilities showMessageHud:@"请输入正确的手机号" duration:1.0];
    }
}
@implementation ToolsClassManager
/**
 *  输入只能是数字
 */
+ (BOOL)validateNumber:(NSString*)number;

/**
 *  正则判断手机号码地址格式
 */
+ (BOOL)isMobileNumber:(NSString *)mobileNum;
#pragma mark - 正则判断手机号码地址格式
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}
#pragma mark - 输入只能是数字
+ (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

相关文章

网友评论

      本文标题:UITextField

      本文链接:https://www.haomeiwen.com/subject/dzkqyttx.html