Restrict NSTextField to only allow numbers

前端 未结 9 1606
[愿得一人]
[愿得一人] 2020-12-23 18:31

How do I restrict a NSTextfield to allow only numbers/integers? I\'ve found questions like this one, but they didn\'t help!

9条回答
  •  感动是毒
    2020-12-23 19:17

    Try to make your own NSNumberFormatter subclass and check the input value in -isPartialStringValid:newEditingString:errorDescription: method.

    @interface OnlyIntegerValueFormatter : NSNumberFormatter
    
    @end
    
    @implementation OnlyIntegerValueFormatter
    
    - (BOOL)isPartialStringValid:(NSString*)partialString newEditingString:(NSString**)newString errorDescription:(NSString**)error
    {
        if([partialString length] == 0) {
            return YES;
        }
    
        NSScanner* scanner = [NSScanner scannerWithString:partialString];
    
        if(!([scanner scanInt:0] && [scanner isAtEnd])) {
            NSBeep();
            return NO;
        }
    
        return YES;
    }
    
    @end
    

    And then set this formatter to your NSTextField:

    OnlyIntegerValueFormatter *formatter = [[[OnlyIntegerValueFormatter alloc] init] autorelease];
    [textField setFormatter:formatter];
    

提交回复
热议问题