Tuesday, March 3, 2015

Cocoa OSX NSTextField Allow Only Integer Value


Recently I was working on MAC OSX application where we have a view with some textfields. Where in few textfields where only numeric values are allowed. In this blog I will explain how to do this.

I used NSNumberFormatter for that. First you have to create a class which extends NSNumberFormatter.

Go to your .m file and add new interface.

@interface OnlyIntegerValueFormatter : NSNumberFormatter


Now implement this interface in same file.

@implementation OnlyIntegerValueFormatter

- (BOOL)isPartialStringValid:(NSString*)partialString newEditingString:(NSString**)newString errorDescription:(NSString**)error
    if([partialString length] == 0) {
        return YES;
    NSScanner* scanner = [NSScanner scannerWithString:partialString];
    if(!([scanner scanInt:0] && [scanner isAtEnd])) {
        return NO;
    return YES;


That's it. Now create instance of OnlyIntegerValueFormatter and assign it to NSTextField. 

OnlyIntegerValueFormatter *formatter = [[OnlyIntegerValueFormatter alloc] init];
[self.onlyIntegerTextField setFormatter:formatter];

That's it. Now if you try to type characters in the textfield, it won't allow it. 

No comments:

Post a Comment