Tuesday, March 3, 2015

Cocoa OSX NSTextField Allow Only Integer Value

Hello,

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


@end

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])) {
        NSBeep();
        return NO;
    }
    
    return YES;
}

@end

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