3

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

SushiHangover
  • 73,120
  • 10
  • 106
  • 165

1 Answers1

6

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

SushiHangover
  • 73,120
  • 10
  • 106
  • 165