I am trying to connect an NSNumberFormatter to an NSTextfield using the formatter outlet of an NSTextField (shown in image below). My formatter subclass is as follows:
#import <Foundation/Foundation.h>
@interface FieldFormatter : NSNumberFormatter
@end
#import "FieldFormatter.h"
@implementation FieldFormatter
- (NSNumberFormatterBehavior)formatterBehavior {
return NSNumberFormatterBehavior10_4;
}
- (NSNumberFormatterStyle)numberStyle {
return NSNumberFormatterDecimalStyle;
}
@end
I get no errors when I run the program but the formatter is not working as it should. When I type a decimal into the text field it rounds up, i.e. 13.8 becomes 14. I can't input decimals at all into the text field.
I can get this to work correctly when using an NSTextField with NSNumberFormatter
in Interface Builder. But I would prefer to do this through code so I can have more control over the format.
So what I'm trying to do is this - Subclass NSNumberFormatter, connect the formatter to text fields in the XIB, then after the user inputs a number into a text field that number is formatted.
Any suggestions would be helpful.
Alloc init your formatter, and then just call setFormatter: on your text field.
FieldFormatter *formatter = [[FieldFormatter alloc] init];
[myTextField setFormatter:formatter];
And, if you're not doing anything with it in IB, you should get rid of that connection and the blue cube that represents your FieldFormatter instance.