NSTextField input validation
NSTextField input validation
- Subject: NSTextField input validation
- From: "Adam Venturella" <email@hidden>
- Date: Mon, 12 Jan 2009 16:22:19 -0800
When a user opts to edit the contents of a Text Cell in a Table View, in
this case, I want to limit their input to numbers only. Looking at
NSNumberFormattter, it would seem that it just formats, it does not restrict
to it's format, which makes sense.
Digging around for a bit, here is the method I ended up with. Could anyone
look this over and let me know if this is the Best way to handle this. If
not, point me a good direction?
I created a subclass of NSTextFieldCell:
@interface NumberOnlyTextCell : NSTextFieldCell
@end
@implementation NumberOnlyTextCell
// Override and cast the textObj into a NSTextView and set it's delegate
- (NSText *)setUpFieldEditorAttributes:(NSText *)textObj
{
[super setUpFieldEditorAttributes:textObj];
// I don't get any errors when I cast this, and this code does work
// So I am going to assume, it's alright to do here:
NSTextView * view = (NSTextView *)textObj;
view.delegate = self;
return textObj;
}
// now add the NSTextViewDelegate that handles input:
- (BOOL)textView:(NSTextView *)aTextView
shouldChangeTextInRange:(NSRange)affectedCharRange
replacementString:(NSString *)replacementString
{
BOOL result = YES;
if(affectedCharRange.length != 1 && ![replacementString isEqualToString:@
""])
{
// I could run this through and NSScanner also, but I figured just using the
NumberFormatter would be faster...
NSNumberFormatter * formatter = [[NSNumberFormatter alloc]
init];
if(![formatter numberFromString:replacementString]){
result = NO;
}
[formatter release];
}
else
{
if([replacementString length] > 0)
{
// I could run this through and NSScanner also, but I figured just using the
NumberFormatter would be faster...
NSNumberFormatter * formatter = [[NSNumberFormatter
alloc] init];
if(![formatter numberFromString:replacementString]){
result = NO;
}
[formatter release];
}
}
if(!result){
NSBeep();
}
return result;
}
@end
So there we have it. Again this does do exactly what I want it to do, if
the user tries to enter a letter or anything not a number, I get an
NSBeep(); It works if the operation is a paste operation or initiated by a
keystroke.
My main question, am I doing the right thing by casting the NSText into a
NSTextView, and is the NumberFormatter the best way to go in order to test
for a valid number or should I go the NSScanner route?
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden