繁体   English   中英

强制NStextField仅接受十六进制值

[英]Force a NStextField to only accept Hex values

我有两个TextFields。 一个只接受数值和其他十六进制值。 我使用NSNumberformatter设置仅数字输入,如:

NSNumberFormatter *formatter;
formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterNoStyle];

然后将其应用于TextField。

我该怎么做但只接受十六进制值? 十六进制我的意思是1234567890ABCDEF。

或者,如果无法完成,如何检查该TextField上的文本是否为十六进制?

谢谢

以前的答案解释了如何使用通知进行操作,并链接到一个问题,该问题显示了在涉及绑定时如何使用键值验证。 另一种方法是编写NSFormatter的子类。 根据您的编写方式,您可以验证用户何时尝试退出该字段,或立即拒绝无效字符。

编辑添加:检查字符串是否为十六进制的一种方法:

NSCharacterSet* nonHex = [[NSCharacterSet
  characterSetWithCharactersInString: @"0123456789ABCDEFabcdef"]
  invertedSet];
NSRange nonHexRange = [aString rangeOfCharacterFromSet: nonHex];
BOOL isHex = (nonHexRange.location == NSNotFound);

请参阅此答案以获得更好的解释 ,但它会是这样的:

- (void)controlTextDidChange:(NSNotification *)aNotification {
    NSError *outError;
    NSControl *textField = [aNotification object];
    NSString *myText = [textField stringValue];

    // check if myText is 0-9 or a-f, do something with it if its not hex.

    // update the NSNextField with the validated text
    [postingObject setStringValue:myText];
}
     - (void)textDidChange:(NSNotification *)aNotification
    {
    //ask the notification for it's sender to return the field object, ask the text field for it's string, if the last char of the string is not valid, delete it and update the string of the field.
//Optionally play the "bell"(alert sound).
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM