Restrict NSTextField to only allow numbers

前端 未结 9 1587
[愿得一人]
[愿得一人] 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:01

    Here is the steps to create the same....

    Just create the ANYCLASS(called SAMPLE) with sub classing the NSNumberFormatter ...

    in .m file write the following code...

     - (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString      **)newString errorDescription:(NSString **)error {
    // Make sure we clear newString and error to ensure old values aren't being used
    if (newString) { *newString = nil;}
    if (error) {*error = nil;}
    
    static NSCharacterSet *nonDecimalCharacters = nil;
    if (nonDecimalCharacters == nil) {
        nonDecimalCharacters = [[NSCharacterSet decimalDigitCharacterSet] invertedSet] ;
    }
    
    if ([partialString length] == 0) {
        return YES; // The empty string is okay (the user might just be deleting everything and starting over)
    } else if ([partialString rangeOfCharacterFromSet:nonDecimalCharacters].location != NSNotFound) {
        return NO; // Non-decimal characters aren't cool!
    }
    
    return YES;
    

    }

    Now.. in your Actual Class set the formatter to your NSTextField object like below...

    NSTextField *mySampleTxtFld;
    

    for this set the Formatter...

    SAMPLE* formatter=[[SAMPLE alloc]init];// create SAMPLE FORMATTER OBJECT 
    
    self.mySampleTxtFld.delegate=self;
    [self.mySampleTxtFld setFormatter:formatter];
    

    Your done!!!

提交回复
热议问题