仅允许在xamarin.mac

时间:2017-02-21 11:28:21

标签: xamarin xamarin.mac

我想放置一个只接受数字(0-9)的文本字段。 如何限制NSTextfield只允许数字/整数?

1 个答案:

答案 0 :(得分:3)

创建NSNumberFormatter子类并查看partialString中收到的IsPartialStringValid您要接受或拒绝的字符。更改newString以删除您不接受的字符。

NSNumberFormatter子类:

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;
    }
}

实施例

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