I don't find any solution how to limit a textfield
do allow only numbers in Monotouch.
Also I want that there a not more than 8 characters.
To implement numeric only UITextField
s in MonoTouch I use this code:
var numberTextField = new UITextField { KeyboardType = UIKeyboardType.NumberPad };
numberTextField.ShouldChangeCharacters = (textField, range, replacement) =>
{
int number;
return replacement.Length == 0 || int.TryParse(replacement, out number);
};
And to limit to a specific amount of characters:
const int maxCharacters = 8;
textField.ShouldChangeCharacters = (textField, range, replacement) =>
{
var newContent = new NSString(textField.Text).Replace(range, new NSString(replacement)).ToString();
return newContent.Length <= maxCharacters;
};
So, combined:
const int maxCharacters = 8;
var numberTextField = new UITextField { KeyboardType = UIKeyboardType.NumberPad };
numberTextField.ShouldChangeCharacters = (textField, range, replacement) =>
{
var newContent = new NSString(textField.Text).Replace(range, new NSString(replacement)).ToString();
int number;
return newContent.Length <= maxCharacters && (replacement.Length == 0 || int.TryParse(replacement, out number));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With