I love Cocoa, but it seems that some simple things are missing. For example, NSTextField doesn’t have the ability to filter text input as the user is typing. A friend reminded me that this is a feature that PowerPlant had ages ago. Cocoa has NSFormatters which allow the field to be validated after text is input, but in many cases, the right way to restrict input is to prevent it from being typed. I like NSFormatters and have created a very complex one to handle multiple currencies in ReceiptWallet, but I realized I needed something else.
So, I present FilteringTextField. The attached code can be freely used in commercial and non-commercial projects. While I’d like some credit in the about box, it isn’t necessary. This code has no warranty and you assume all risk for using it.
The subclass of NSTextField, has 3 methods.
- (void) setAcceptableCharacterSet:(NSCharacterSet *) inCharacterSet; - (void) setMaximumLength:(int) inLength; - (void) setMaximumValue:(int) inValue;
The first lets you set the characters that can be typed; anything that isn’t in the set is eaten. The second, only allows x characters to be typed and the last limits the value if the user is typing in a number. This class can easily be extended to handle other constraints. Pasting in text is also filtered.
If anyone finds problems with this code, please let me know.
NSFormatter can filter (and modify) the string as it is entered. The built-in formatters don\’t do this, but you can write a custom one which does.
Interesting; I asked a few people and they didn’t know how to do what I wanted. I just double checked the NSFormatter docs and it looks like the method: isPartialStringValid:newEditingString:errorDescription: will do the trick.
Thanks for pointing me in the right direction.
thank you for sharing the code it works like a charm. 🙂