0

I'm trying to use a class I have which overrides NSFormatter in an OS X app. I tried an example from a book but it's from an older version of XCode. My problem is I don't know how to set my NSTextfield's formatter. I'm not sure if something changed now that Xcoded has the IB built in or I'm doing something else wrong. It looks like you used to be able to control click your text field and it would bring up a menu. In the outlets section of the menu it says I'm suppose to see a "formatter" selection. That is not listed in my outlets section of the menu.

I don't think it makes a difference, but my NSTextfield is in a NSScrollview. I'm still very new to Cocoa (coming from a C# and C++ background).

JonF
  • 2,336
  • 6
  • 38
  • 57

1 Answers1

1

You can simply subclass NSNumberFormatter like this:

in .h

@interface NumberFormatterSubclass : NSNumberFormatter {

}

@end

in .m

@implementation NumberFormatterSubclass


- (BOOL)isPartialStringValid:(NSString **)partialString
   proposedSelectedRange:(NSRangePointer)proposedSelRange
          originalString:(NSString *)origString
   originalSelectedRange:(NSRange)origSelRange
        errorDescription:(NSString **)error 
{

    if ([*partialString length] > 4) { 
        return NO;
    }


    return YES;
}

Don't forget to add NSNumberFormatter on Your NSTextField and change NSNumberFormatter class to Your created subclass in identity inspector.

Justin Boo
  • 10,132
  • 8
  • 50
  • 71
  • Thanks for the suggestion but the text field is not limited to numbers. I found this solution to creating a formatter class http://stackoverflow.com/questions/827014/how-to-limit-nstextfield-text-length-and-keep-it-always-upper-case. I just can't find how to link the nstextfield to any formatter – JonF Feb 20 '12 at 20:41
  • It's not limiting numbers.. It's limiting letters and and numbers. It's limiting to 4 symbols letters or numbers. And You can link formatter by dragging it on NSTextField and then change formatter class to Your created subclass in identity inspector how I was said in my post earlear. Furthermore if You don't like how it sounds "NSNumberFormatter" use "NSFormatter" same my writed code will work! – Justin Boo Feb 20 '12 at 22:01
  • 1
    When subclassing an NSFormatter you must also implement the methods: stringForObjectValue: and getObjectValue:forString:errorDescription: See "Creating a Custom Formatter" https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/CreatingACustomFormatter.html#//apple_ref/doc/uid/20000196 – ctpenrose Apr 26 '12 at 18:10