Verificherà un UITextField per un'e-mail e un numero di telefono corretti di 10 cifre o meno.
Aggiungere questo metodo allo textFields delegate quindi verificare se i caratteri che sta per cambiare devono essere aggiunti o meno.
ritorno YES
o NO
a seconda del campo di testo, quanti caratteri sono attualmente in essa, e quali caratteri si vuole aggiungere:
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC @"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *unacceptedInput = nil;
switch (textField.tag) {
// Assuming EMAIL_TextField.tag == 1001
case 1001:
if ([[textField.text componentsSeparatedByString:@"@"] count] > 1)
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
else
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}[email protected]"]] invertedSet];
break;
// Assuming PHONE_textField.tag == 1002
case 1002:
if (textField.text.length + string.length > 10) {
return NO;
}
unacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
break;
default:
unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
break;
}
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
Inoltre, prova anche questi 2 articoli:
Auto-formatting phone number UITextField on the iPhone
PhoneNumberFormatter.
sembra buono, non ho guardato nella delegato campo di testo prima. – sunkencity
chown, funziona alla grande ma non sembra gestire gli eventi chiave di cancellazione. Restituisce NO se il telefono è> = 10 quindi non cambia dopo l'eliminazione – spentak
Oh, sei corretto. Sostituisci 'if (textField.text.length> = 10)' con 'if (textField.text.length + string.length> 10)' – chown