Restrict NSTextField input to numeric only? NSNumberformatter

后端 未结 5 1687
心在旅途
心在旅途 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:17

    NPAssoc's Answer did help me and I did a little change to the code which did not use isMatchedByRegex function.

    // Make sure the user has typed a valid number so far.
    - (void)controlTextDidChange:(NSNotification *)obj
    {
        if (obj.object == self->number)
        {
            NSString *countValue = number.stringValue;        
            if ([countValue length] > 0) {
                if ([[countValue substringFromIndex:[countValue length]-1] integerValue] > 0 ||
                    [[countValue substringFromIndex:[countValue length]-1] isEqualToString:@"0"])
                {
                    self.lastNumber = number.stringValue;
                }
                else
                {
                    number.stringValue = self.lastNumber;
                    NSBeep();
                }
            }
        }
    }
    

    PS:Use the [self setIntValue:[self intValue]] limited the length of the input.

提交回复
热议问题