iOS UITextField输入手机号时自动添加空格

需求是用户填写手机号时自动添加空格, 如:180 0000 0001

实现:

{
    NSInteger _num;
}

    _num = 0;
    [self.mobileTextField addTarget:self action:@selector(textFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];

// 以3 4 4格式显示手机号: 133 3333 4567
-(void)textFieldDidEditing:(UITextField *)textField{
    if (textField == self.mobileTextField) {
        if (textField.text.length > _num) {
            if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
                NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
                [str insertString:@" " atIndex:(textField.text.length-1)];
                textField.text = str;
            }if (textField.text.length >= 13 ) {//输入完成
                textField.text = [textField.text substringToIndex:13];
                [textField resignFirstResponder];
            }
            _num = textField.text.length;
            
        }else if (textField.text.length < _num){//删除
            if (textField.text.length == 4 || textField.text.length == 9) {
                textField.text = [NSString stringWithFormat:@"%@",textField.text];
                textField.text = [textField.text substringToIndex:(textField.text.length-1)];
            }
            _num = textField.text.length;
        }
    }
}

使用时获取真实的手机号:

NSString *phone = [self.bindingView.mobileTextField.text stringByReplacingOccurrencesOfString:@" "withString:@""];




你可能感兴趣的:(iOS UITextField输入手机号时自动添加空格)