Restrict NSTextField to only allow numbers

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

    Here's a solution with filtering. Give a delegate and an outlet to textfield and set controlTextDidChange method.

    - (void)controlTextDidChange:(NSNotification *)aNotification {
    
        NSTextField *textfield = [notification object];
        NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    
        char *stringResult = malloc([textfield.stringValue length]);
        int cpt=0;
        for (int i = 0; i < [textfield.stringValue length]; i++) {
            unichar c = [textfield.stringValue characterAtIndex:i];
            if ([charSet characterIsMember:c]) {
                stringResult[cpt]=c;
                cpt++;
            }
        }
        stringResult[cpt]='\0';
        textfield.stringValue = [NSString stringWithUTF8String:stringResult];
        free(stringResult);
    }
    

提交回复
热议问题