Force NStextField to Hex

I have two text fields. Only numerical values ​​and other hexadecimal values ​​are accepted. I use NSNumberformatter to set numeric input, for example:

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

And then apply it to the TextField.

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

Alternatively, if this is not possible, how can I verify that the text on this TextField is hex?

thanks

+4
source share
3 answers

Look at this answer for a much better explanation , but it will be something like this:

 - (void)controlTextDidChange:(NSNotification *)aNotification { NSError *outError; NSControl *textField = [aNotification object]; NSString *myText = [textField stringValue]; // check if myText is 0-9 or af, do something with it if its not hex. // update the NSNextField with the validated text [postingObject setStringValue:myText]; } 
+1
source

The previous answers explain how to do this using notifications and refer to the question of how to use key value verification when binding. Another approach is to write a subclass of NSFormatter . Depending on how you write it, you can check when the user tries to leave the field or immediately reject invalid characters.

Edit to add: one way to check if a string is hexadecimal:

 NSCharacterSet* nonHex = [[NSCharacterSet characterSetWithCharactersInString: @"0123456789ABCDEFabcdef"] invertedSet]; NSRange nonHexRange = [aString rangeOfCharacterFromSet: nonHex]; BOOL isHex = (nonHexRange.location == NSNotFound); 
+3
source
  - (void)textDidChange:(NSNotification *)aNotification { //ask the notification for it sender to return the field object, ask the text field for it 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). } 
0
source

All Articles