强制NStextField仅接受十六进制值

时间:2011-10-05 20:41:04

标签: objective-c macos cocoa

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

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

然后将其应用于TextField。

我如何做同样但只接受十六进制值?按十六进制,我的意思是1234567890ABCDEF。

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

由于

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

See this answer for a much better explanation,但它会是这样的:

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

答案 2 :(得分:0)

     - (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).
    }