How to limit NSTextField text length and keep it always upper case?

后端 未结 6 1459
无人及你
无人及你 2020-12-01 02:47

Need to have an NSTextField with a text limit of 4 characters maximum and show always in upper case but can\'t figure out a good way of achieving that. I\'ve tried to do it

6条回答
  •  遥遥无期
    2020-12-01 03:35

    The custom NSFormatter that Graham Lee suggested is the best approach.

    A simple kludge would be to set your view controller as the text field's delegate then just block any edit that involves non-uppercase or makes the length longer than 4:

    - (BOOL)textField:(UITextField *)textField
        shouldChangeCharactersInRange:(NSRange)range
        replacementString:(NSString *)string
    {
        NSMutableString *newValue = [[textField.text mutableCopy] autorelease];
        [newValue replaceCharactersInRange:range withString:string];
    
        NSCharacterSet *nonUppercase =
            [[NSCharacterSet uppercaseLetterCharacterSet] invertedSet];
        if ([newValue length] > 4 ||
            [newValue rangeOfCharacterFromSet:nonUppercase].location !=
                NSNotFound)
        {
           return NO;
        }
    
        return YES;
    }
    

提交回复
热议问题