我想放置一个只接受数字(0-9)的文本字段。 如何限制NSTextfield只允许数字/整数?
答案 0 :(得分:3)
创建NSNumberFormatter
子类并查看partialString
中收到的IsPartialStringValid
您要接受或拒绝的字符。更改newString
以删除您不接受的字符。
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