UITextField Should accept number only values

前端 未结 14 1174
有刺的猬
有刺的猬 2020-12-08 09:50

I have UITexfields i want that it should accept only number other shows alert that enter a numeric value. I want that motionSicknessTextFiled should only accept number

相关标签:
14条回答
  • 2020-12-08 10:25

    Another option of entering only numeric values into your text field is by selecting the keyboard type attribute of the corresponding textfield. Attaching the screenshot for reference.

    0 讨论(0)
  • 2020-12-08 10:27
    [textField setKeyboardType:UIKeyboardTypeNumberPad];
    
    0 讨论(0)
  • 2020-12-08 10:27

    swift 4

    This allows only number input and you can also set character limitation

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
      let compSepByCharInSet = string.components(separatedBy: aSet)
      let numberFiltered = compSepByCharInSet.joined(separator: "")
    
      if string == numberFiltered {
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        return updatedText.count <= 10
      } else {
        return false
      }
    }
    
    0 讨论(0)
  • 2020-12-08 10:27

    this is the function which checks for the String contains Numeric value only

    +(BOOL) checkforNumeric:(NSString*) str
    {
        NSString *strMatchstring=@"\\b([0-9%_.+\\-]+)\\b"; 
        NSPredicate *textpredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@", strMatchstring];
    
        if(![textpredicate evaluateWithObject:str])
        {
            //////NSLog(@"Invalid email address found");
            UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"please enter valid text." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close",nil];
            [objAlert show];
            [objAlert release];
            return FALSE;
        }
        return TRUE;
    }
    

    check it on submit button.

    0 讨论(0)
  • 2020-12-08 10:27

    I just modified the answer of Michael and made it a little bit easier to implement. Just make sure that the delegate of your UITextfield is set to itself.

    yourTxtField.delegate = self;
    

    Furthermore copy & paste this code into your main file.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    
        if (textField == yourTxtField) {
            NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
            NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
    
            BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
                return stringIsValid;
            }else {
                return YES;
            }
        }
    

    If you want to allow the use of the spacebar just put in a blank space at the end of the CharactersInString, just like so:

    @"0123456789" -> @"0123456789 "
    

    Additionally:

    If you want to restrict the length of the string just replace the if-function with following:

    if (textField == yourTxtField) {
            NSUInteger newLength = [textField.text length] + [string length] - range.length;
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            return (([string isEqualToString:filtered])&&(newLength <= 10));
    
        }
    

    In my case the "10" at the end represents the limit of characters.

    Cheers! :)

    0 讨论(0)
  • 2020-12-08 10:28

    Swift 4.2 port of the best answer here by @almas-adlibek

    A bunch of configuration variables:

    private let kMaxTextLength = 8
    private let kZeroDotted = "0."
    private let kZero = "0"
    private let kDoubleDot = ".."
    private let kDot = "."
    private let kPeriod = ","
    

    Now the Swift 4 converted part of the code.

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        guard let oldText = textField.text, let swiftRange = Range(range, in: oldText) else {
            return true
        }
    
        let newText = oldText.replacingCharacters(in: swiftRange, with: string)
    
        var currentText =  textField.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    
        // Change the "," (appears in other locale keyboards, such as russian) key ot "."
        currentText = currentText?.replacingOccurrences(of: kPeriod, with: kDot)
    
        // Check the statements of decimal value.
        if (newText == kDot) {
            textField.text = kZeroDotted;
            return false
        }
    
        if (newText.range(of: kDoubleDot) != nil) {
            textField.text = newText.replacingOccurrences(of: kDoubleDot, with: kDot);
            return false
        }
    
        // If second dot is typed, ignore it.
        let dots = newText.components(separatedBy: kDot)
        if(dots.count > 2) {
            textField.text = currentText;
            return false
        }
    
        // If first character is zero and second character is > 0, replace first with second. 05 => 5;
        if(newText.count == 2) {
            if(newText[0...0] == kZero && newText != kZeroDotted) {
                textField.text = newText[1...1]
                return false
            }
        }
    
        // Check the max characters typed.
        let oldLength = textField.text?.count ?? 0
        let replacementLength = string.count
        let rangeLength = range.length
    
        let newLength = oldLength - rangeLength + replacementLength;
        let returnKey = string.rangeOfCharacter(from: CharacterSet.newlines) != nil
    
        return newLength <= kMaxTextLength || returnKey;
    }
    
    0 讨论(0)
提交回复
热议问题