Restrict NSTextField input to numeric only? NSNumberformatter

后端 未结 5 1673
心在旅途
心在旅途 2020-12-06 02:44

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

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 03:29

    Here are the steps to create the same:

    Just create the ANYCLASS (called SAMPLE) subclassing the NSNumberFormatter, and in the .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 this:

    NSTextField *mySampleTxtFld;
    

    And for this set the Formatter:

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

    You’re done!

提交回复
热议问题