Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monotouch UITextField only numbers

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.

like image 459
user1868675 Avatar asked Dec 21 '22 11:12

user1868675


1 Answers

To implement numeric only UITextFields 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));
    };
like image 61
redent84 Avatar answered Jan 12 '23 13:01

redent84