Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)

前端 未结 28 2093
长情又很酷
长情又很酷 2020-11-28 01:19

I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the

28条回答
  •  粉色の甜心
    2020-11-28 01:38

    in my case, we have to formating iban number. i think, the below code block help you

    Firstly, check the user enterted value is valid

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
        if(textField == self.ibanTextField){
    
               BOOL shouldChange =  ([Help checkTextFieldForIBAN:[NSString stringWithFormat:@"%@%@",textField.text,string]]);
     }
    }
    

    Secondly, you can see iban formated method just like below. Our iban formated begin 2 letter.

    +(BOOL)checkTextFieldForIBAN:(NSString*)string{
    
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    
        if ([string length] <= 26) {
    
            if ([string length] > 2) {
    
                if ([self isLetter:[string substringToIndex:2]]) {
    
                    if ([self isInteger:[string substringFromIndex:2]])
                        return YES;
                    else
                        return NO;
    
                }else {
    
                    return NO;
                }
            }else{
    
                return [self isLetter:string];
            }
    
        }
        else {
    
            return NO;
        }
    
        return YES;
    }
    

提交回复
热议问题