Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only Numbers for NsTextField input in xamarin.mac

I want to place a text field that only accepts numbers (0-9). How do I restrict a NSTextfield to allow only numbers/integers?

like image 549
Mohammed Abid Avatar asked Jan 23 '26 23:01

Mohammed Abid


1 Answers

Create a NSNumberFormatter subclass and review the partialString received in the IsPartialStringValid for characters that you wish to accept or reject. Alter the newString to remove characters that you are not accepting.

NSNumberFormatter subclass:

class NumberOnlyFormattter : NSNumberFormatter
{
    public override bool IsPartialStringValid(string partialString, out string newString, out NSString error)
    {
        newString = partialString;
        error = new NSString("");
        if (partialString.Length == 0)
            return true;

        // you could allow use partialString.All(c => c >= '0' && c <= '9') if internationalization is not a concern
        if (partialString.All(char.IsDigit))
            return true;
        newString = new string(partialString.Where(char.IsDigit).ToArray());
        return false;
    }
}

Example:

var text = new NSTextField(new CGRect(50, 50, 100, 40));
text.Formatter = new NumberOnlyFormattter();
View.AddSubview(text);

re: https://developer.apple.com/reference/foundation/numberformatter

like image 119
SushiHangover Avatar answered Jan 26 '26 17:01

SushiHangover



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!