Subclassing NSTextField to Allow Only Numbers

Example project available on GitHub – CINumberField

Yes, I know that one may use NSNumberFormatter to achieve a similar result – but what I don’t like about about that solution is this:

If a user types non-numeric characters into the NSTextField and attempts to tab away from the field, they get the default error sound and their tab attempt is denied.

To me this isn’t user friendly.

I figured I’d take a Javascript-esque approach to the problem: when the user has finished interacting with the text field, check whether said content is numeric. If it isn’t, beat it until it learns.

Witness the incredible simplicity:

NumberField.h

//  NumberField.h
//  Created by Michael Robinson (Code of Interest) on 28/11/10.
#import <Cocoa/Cocoa.h>
 
@interface NumberField : NSTextField { }
 
-(void) textDidEndEditing:(NSNotification *)aNotification;
 
@end

NumberField.m

//  NumberField.m
//  Created by Michael Robinson (Code of Interest) on 28/11/10.
#import <NumberField.h>
 
@implementation NumberField
 
-(void) textDidEndEditing:(NSNotification *)aNotification {
	// replace content with its intValue ( or process the input's value differently )
	[self setIntValue:[self intValue]];
	// make sure the notification is sent back to any delegate
	[[self delegate] controlTextDidEndEditing:aNotification];
}
@end

To use the class, open your NIB in Interface Builder and select the NSTextField you want to limit to numbers only, open the Inspector, open the Identity tab, and paste the name of your new class in the “Class” text field.

Related posts:

  1. Resizing NSTextField to Fit Content The NSPopOver, a new addition to the Cocoa toolkit since OS X 10.7, is an excellent way to give the user feedback on actions requiring their input. In my use...
  2. More Usability-Oriented Method for Disabling an NSTabViewItem Jump to tutorial I was unable to find a way to easily disable an NSTabViewItem – before implementing the method described below, I achieved this by simply returning “NO” from...

Comments (15) | Trackback