How can I limit the number of decimal points in a UITextField?

后端 未结 15 2251
说谎
说谎 2020-12-01 05:20

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal

相关标签:
15条回答
  • 2020-12-01 05:46

    Swift 4

    max number of Integers Numbers is 4 i.e., 9999, and max decimal digits limit is 2. So, max number can be 9999.99

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    
        // 100 is the tag value of our textfield
        /*or you may use "if textfield == myTextField{" if you have an IBOutlet to that textfield */
        if textField.tag == 100 {
    
            //max length limit of text is 8
            if textField.text!.count > 8 && string != "" {
                return false
            }
    
            let maxLength = 8
            let currentString: NSString = textField.text! as NSString 
    

    // Use following code If you are inputting price to that text field and want $ to get inserted automatically at start when user starts typing in that textfield or you may put some other character at start instead of $. Otherwise comment the following 3 lines of if condition code

            if currentString.length == 0 {
                priceTextField.text = "$"
            }
    

    //new string after inserting the new entered characters

            let newString: NSString =
                currentString.replacingCharacters(in: range, with: string) as NSString
    
    
            if newString.length > maxLength{
                return false
            }
    
            if (textField.text!.range(of: ".") != nil) {
                let numStr = newString.components(separatedBy: ".")
                if numStr.count>1{
                    let decStr = numStr[1]
                    if decStr.length > 2{
                        return false
                    }
                }
            }
    
            var priceStr: String = newString as String
    
            if (textField.text!.range(of: "$") != nil) {
                priceStr = priceStr.replacingOccurrences(of: "$", with: "")
            }
    
            let price: Double = Double(priceStr) ?? 0
    
            if price > 9999.99{
                return false
            }
    
            switch string {
            case "0","1","2","3","4","5","6","7","8","9":
                return true
            case ".":
                let array = Array(textField.text!)
                var decimalCount = 0
                for character in array {
                    if character == "." {
                        decimalCount = decimalCount + 1
                    }
                }
    
                if decimalCount == 1 {
                    return false
                } else {
                    return true
                }
            default:
    
                let array = Array(string)
                if array.count == 0 {
                    return true
                }
                return false
            }
        }
        return true
    }
    
    0 讨论(0)
  • 2020-12-01 05:48

    Try this :-

    public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    
        if(text == "," || text == "." ){
            let countdots = textView.text!.componentsSeparatedByString(".").count - 1
    
            if countdots > 0 && (text == "." || text == "," )
            {
                return false
            }
        }
    
        return true
    }
    
    0 讨论(0)
  • 2020-12-01 05:49

    Swift 3 Implement this UITextFieldDelegate method to prevent user from typing an invalid number:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (textField.text ?? "") as NSString
        let newText = text.replacingCharacters(in: range, with: string)
        if let regex = try? NSRegularExpression(pattern: "^[0-9]*((\\.|,)[0-9]*)?$", options: .caseInsensitive) {
            return regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
        }
        return false
    }
    

    It is working with both comma or dot as decimal separator. You can also limit number of fraction digits using this pattern: "^[0-9]*((\\.|,)[0-9]{0,2})?$" (in this case 2).

    0 讨论(0)
  • 2020-12-01 05:50

    Building on the accepted answer, the following approach validates three cases that are helpful when dealing with money formats:

    1. Extremely large amounts
    2. More than 2 characters after the decimal point
    3. More than 1 decimal points

    Make sure your text field's delegate is set properly, your class conforms to the UITextField protocol, and add the following delegate method.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
      // Check for deletion of the $ sign
      if (range.location == 0 && [textField.text hasPrefix:@"$"])
        return NO;
    
      NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
      NSArray *stringsArray = [updatedText componentsSeparatedByString:@"."];
    
      // Check for an absurdly large amount
      if (stringsArray.count > 0)
      {
        NSString *dollarAmount = stringsArray[0];
        if (dollarAmount.length > 6)
          return NO;
      }
    
      // Check for more than 2 chars after the decimal point
      if (stringsArray.count > 1)
      {
        NSString *centAmount = stringsArray[1];
        if (centAmount.length > 2)
          return NO;
      }
    
      // Check for a second decimal point
      if (stringsArray.count > 2)
        return NO;
    
      return YES;
    }
    
    0 讨论(0)
  • 2020-12-01 05:57

    Swift 4

    The efficient and easy way to avoid multiple decimal points (. or ,) in UITextField:

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if(string == "," || string == "." ){
    
            if ((textField.text?.contains(","))! || (textField.text?.contains("."))!){
                return false
            }
        }
        return true
    }
    
    0 讨论(0)
  • 2020-12-01 06:00

    Swift 3

    No need to create an array and check count. Limit user can only place 1 decimal mark like this.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (textField.text?.contains("."))! && string.contains(".")
        {
            return false
        }
        else
        {
            return true
        }
    }
    
    0 讨论(0)
提交回复
热议问题