Domanda

This may be a simple question but I've been unable to find the answer. I have an app where I would like to prevent users from entering anything but numeric values.

In interface builder I can set the keyboard to present itself with numbers, but the user can still switch it to alphabet at runtime. I would like to be able to prevent the user from doing this. Does anyone know how to prevent the alphabet keyboard?

Thanks!

È stato utile?

Soluzione

Maybe it is not necessary you modify the keyboard. A has been suggested, you can instead modify the input. Once the user notices, that alphabetical input does not do anything, she will presumably stop trying.

This will filter out all but the numbers:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range 
    replacementString:(NSString *)string 
{
  NSString *numbersOnly = [[string componentsSeparatedByCharactersInSet:
     [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
     componentsJoinedByString:@""];
  return [string isEqualToString:numbersOnly];
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top