简体   繁体   中英

Force a NStextField to only accept Hex values

I have two TextFields. One accepts only numerical values and the other hex values. I am using NSNumberformatter to set the numerical-only input, like:

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

And then apply it to the TextField.

How do I do the same but only accepting Hex values? By hex I mean 1234567890ABCDEF.

Alternatively, if it cannot be done, how do I check that the text on that TextField is hex?

Thanks

Previous answers explain how to do it using notifications, and link to a question showing how to use key-value validation when binding is involved. Yet another approach is to write a subclass of NSFormatter . Depending on how you write it, you can validate when the user tries to exit the field, or reject invalid characters immediately.

Edit to add: one way to check whether a string is hex:

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

See this answer for a much better explanation , but it would be something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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