Subclassing NSTextField to Allow Only Numbers


This post was originally published in 2010
It may contain stale & outdated information. Or it may have grown more awesome with age, like the author.

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


//  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];

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.

Comments (17) | Trackback