如何在UITextField

时间:2016-01-20 07:07:25

标签: ios objective-c string uitextfield

我在-中使用输入字符后尝试添加UITextField。情况是添加信用卡/借记卡号码。我已经四处搜索,但根据我的知识,这些方法无效。我已将19方法中的16个卡号和3个-的{​​{1}}个字符的限制设置为:

delegate

所以现在- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSUInteger length = [[textField text] length] - range.length + string.length; return textField.text.length <=19; } 正在给我一个确切的长度,如果当时length。现在工作正常我需要知道如果该字段在字段中达到UITextField37添加11,我应该写什么。所有输入的卡片都采用此格式-,因此我尝试在4个字符后添加xxxx-xxxx-xxxx-xxxx。 我也在-方法中尝试了这个方法,但它没有用:

delegate

3 个答案:

答案 0 :(得分:1)

在委托方法中尝试这是另一种方法

if (textField.text.length < 19 && ![string isEqualToString:@""]) {
    NSString *tempoText = textField.text;
    tempoText = [tempoText stringByReplacingOccurrencesOfString:@"-" withString:@""];

    if (tempoText.length >= 4) {
        NSMutableString *mutString = [tempoText mutableCopy];
        NSUInteger len = mutString.length / 4;

        int j = 0;
        for (int i = 1; i <= len; i ++) {

            NSUInteger index = 4 * i;
            index += j;
            j++;
            [mutString insertString:@"-" atIndex:index];

        }

        tempoText = mutString;
    }

    [textField setText:tempoText];
    return YES;
}

答案 1 :(得分:0)

https://github.com/stripe/PaymentKit/tree/master/PaymentKit

将此第三方库用于信用卡/借记卡,这只是一个击球手,只需使用。

答案 2 :(得分:0)

试试这个会起作用

   - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ; 
    if([string length]==0)
    {
        [formatter setGroupingSeparator:@"-"];
        [formatter setGroupingSize:4];
        [formatter setUsesGroupingSeparator:YES];
        [formatter setSecondaryGroupingSize:2];
        NSString *num = textField.text ;
        num= [num stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
        [formatter release];
        textField.text=str;
        NSLog(@"%@",str);
        return YES;
    }
    else {
        [formatter setGroupingSeparator:@"-"];
        [formatter setGroupingSize:2];
        [formatter setUsesGroupingSeparator:YES];
        [formatter setSecondaryGroupingSize:2];
        NSString *num = textField.text ;
        if(![num isEqualToString:@""])
        {
            num= [num stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
            [formatter release];
            textField.text=str;
        }

        //NSLog(@"%@",str);
        return YES;
    }

    //[formatter setLenient:YES];

}