Help me please if you can.
I created formater for my text field and then in ViewController I am trying to set it:
OnlyNeddedNumbers *numbersOnly = [[OnlyNeddedNumbers alloc] init];
[self.betAmount setFormatter:numbersOnly];
but when I start the app I can't set dot or comma. The aim was allow user to set only double values into the NSTextField
@interface OnlyNeddedNumbers : NSNumberFormatter
@end
@implementation OnlyNeddedNumbers
- (BOOL)isPartialStringValid:(NSString*)partialString newEditingString:(NSString**)newString errorDescription:(NSString**)error
{
if([partialString length] == 0) {
return NO;
}
NSString *scanString = [NSString stringWithFormat:@"%@", [partialString stringByReplacingOccurrencesOfString:@"," withString:@""]];
scanString = [scanString stringByReplacingOccurrencesOfString:@"." withString:@""];
NSScanner* scanner = [NSScanner scannerWithString:scanString];
if(!([scanner scanInt:0] && [scanner isAtEnd])) {
NSBeep();
return NO;
} else if ([scanString isEqualToString:@"0"]) {
NSBeep();
return NO;
}
return YES;
}
@end
You don't need special subclass. Your aim is
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setDecimalSeparator:@","];
[formatter setMinimum:@(-100000)];
[formatter setMaximum:@(100000)];
When you set minimum and maximum it will validate the value automatically. No other code required.
Remember 0.00 is also a valid double value. You can also test for the value [object doubleValue] -> I would consider this as correct approach. If a user inserts text than it will be converted to double number 0.