I am trying to add - after use enter for characters in UITextField. The situation is adding a credit/debit card number. I've searched around but the methods are not valid as per my knowledge. I've set the limit to 19 characters that is 16 card numbers and 3 - in the delegate method as:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger length = [[textField text] length] - range.length + string.length;
return textField.text.length <=19;
}
So now the length is giving me the exact length if UITextField at that time. Which is working fine now I need to know what should I write if this field reaches 3, 7 or 11 add - in the field. All the cards that will be entered are in this format xxxx-xxxx-xxxx-xxxx so that is what I'm trying to do adding - after 4 characters.
I've also tried this inside delegate method but it didn't work:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGroupingSeparator:@"-"];
[formatter setGroupingSize:4];
[formatter setUsesGroupingSeparator:YES];
NSString *num = textField.text ;
num= [num stringByReplacingOccurrencesOfString:@"" withString:@"-"];
NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
textField.text=str;
NSLog(@"%@",str);
return textField.text.length <=19;