martedì 23 giugno 2015

Numero massimo di caratteri consentiti in una UITextField

L'esempio permette di definire il numero massimo di caratteri consentiti in una UITextField per Iphone.
I campi testo nell'esempio sono due che hanno rispettivamente tag=210 e tag=200.
Con Xcode utilizzare queste righe dove verrano controllati entrambi i campi testo:

//define max chars for UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
 
    //[textField setText:[textField.text uppercaseString]]; //all text in uppercase
 
    if(textField.tag==210){
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength > 3) ? NO : YES; //max 3 chars
    }
    else if(textField.tag==200){
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength > 10) ? NO : YES; //max 10 chars
    }
    else{
        return YES;
    }   
}