UITextField - Allow only numbers and punctuation input/keypad

前端 未结 4 790
不思量自难忘°
不思量自难忘° 2020-12-30 10:16

I have tried the code below but that only allows for numbers on the keypad to be inputted. My app requires the keypad to use a period/full stop (for money transactions). The

相关标签:
4条回答
  • 2020-12-30 10:37

    In Swift 3:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let allowedCharacters = "0123456789!@#$%^&*()_+~:{}|\"?><\\`,./;'[]=-"
        return allowedCharacters.contains(string) || range.length == 1
    }
    
    0 讨论(0)
  • 2020-12-30 10:38

    Just use

    [textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
    

    after creating your textfield.

    0 讨论(0)
  • 2020-12-30 10:42

    Try this

    Make a macro

    #define ACCEPTABLE_CHARACTERS @"0123456789."
    

    And use it

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    
        if (textField==textFieldAmount)
        {
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
    
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    
            return [string isEqualToString:filtered];
        }
        return YES;
    }
    
    0 讨论(0)
  • 2020-12-30 10:43

    How about a custom character set? Something like this:

    NSCharacterSet *testChars = [NSCharacterSet characterSetWithCharactersInString:@"0123456789+*#-() "];
    

    Because setting the keyboard type is pretty useless on iPad...

    0 讨论(0)
提交回复
热议问题