I\'m just getting started up with Mac App Development and so far everything is good well, I\'m just having problems trying to get a NSTextField to only accept numbers for th
Here's an alternative implementation:
+ (BOOL)stringIsNumber:(NSString *)str {
BOOL valid;
double holder;
NSScanner *scan = [NSScanner scannerWithString: str];
valid = [scan scanDouble:&holder] && [scan isAtEnd];
return valid;
}
+ (NSString *)numericStringFromString:(NSString *)string {
NSString *digitsString = string;
if (![YOURCLASSNAME stringIsNumber:string]) {
NSUInteger length = [string length];
if (length > 0) {
digitsString = [string substringToIndex:length - 1];
if (![YOURCLASSNAME stringIsNumber:digitsString]) {
digitsString = [YOURCLASSNAME numericStringFromString:digitsString];
}
}
}
return digitsString;
}
Then in my controller class, I implement controlTextDidChange:
- (void)controlTextDidChange:(NSNotification *)obj {
NSString *digitsString = [YOURCLASSNAME numericStringFromString:self.currentCellView.textField.stringValue];
if (digitsString) {
self.currentCellView.textField.stringValue = digitsString;
} else {
self.currentCellView.textField.stringValue = @"";
}
}
The benefit of this approach is that if you paste text into your number field, this will strip out all the non numeric characters from the end of the string until you're left with just a number. Plus it supports an arbitrarily long series of digits. Some of the other approaches would not support putting in a series of digits that couldn't be held in an NSInteger.
I know this approach could certainly be improved though.