如何在swift 4中将文本字段输入限制为2位小数?

Kaw*_*iKx 7 ios swift

我有一个文本字段,我想将条目限制为最多2位小数.

允许的数字如12.34但不是12.345

我该怎么做?

Cod*_*ent 23

将控制器设置为文本字段的委托,并检查建议的字符串是否满足您的要求:

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
    textField.keyboardType = .decimalPad
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let oldText = textField.text, let r = Range(range, in: oldText) else {
        return true
    }

    let newText = oldText.replacingCharacters(in: r, with: string)
    let isNumeric = newText.isEmpty || (Double(newText) != nil)
    let numberOfDots = newText.components(separatedBy: ".").count - 1

    let numberOfDecimalDigits: Int
    if let dotIndex = newText.index(of: ".") {
        numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
    } else {
        numberOfDecimalDigits = 0
    }

    return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
}
Run Code Online (Sandbox Code Playgroud)

  • 没有一本书可以涵盖所有内容。Big Nerd Ranch 的那本书很好地介绍了 Swift 和 iOS 编程。编程是不断学习。您会在其他书籍或 StackOverflow 等网站上找到缺失的部分:) (2认同)

Mih*_*ari 6

各位大侠,解决办法如下:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let dotString = "."

        if let text = textField.text {
            let isDeleteKey = string.isEmpty

            if !isDeleteKey {
                if text.contains(dotString) {
                    if text.components(separatedBy: dotString)[1].count == 2 {

                                return false

                    }

                }

            }
        }
  }
Run Code Online (Sandbox Code Playgroud)


小智 5

在斯威夫特 4 中。

TextField 有 10 位限制和小数点后 2 位限制(您可以更改限制)。点将只允许在 textField 中出现一次。

class ViewController: UIViewController,UITextFieldDelegate {

    var dotLocation = Int()

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {


        let nonNumberSet = CharacterSet(charactersIn: "0123456789.").inverted

        if Int(range.length) == 0 && string.count == 0 {
            return true
        }

        if (string == ".") {
            if Int(range.location) == 0 {
                return false
            }
            if dotLocation == 0 {
                dotLocation = range.location
                return true
            } else {
                return false
            }
        }

        if range.location == dotLocation && string.count == 0 {
            dotLocation = 0
        }

        if dotLocation > 0 && range.location > dotLocation + 2 {
            return false
        }

        if range.location >= 10 {

            if dotLocation >= 10 || string.count == 0 {
                return true
            } else if range.location > dotLocation + 2 {
                return false
            }

            var newValue = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
            newValue = newValue?.components(separatedBy: nonNumberSet).joined(separator: "")
            textField.text = newValue

            return false

        } else {
            return true
        }

    }

}
Run Code Online (Sandbox Code Playgroud)


小智 5

只允许使用两位小数,并且只允许使用一个“.”。允许

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

                    let text: NSString = textField.text! as NSString
                    let resultString = text.replacingCharacters(in: range, with: string)


        //Check the specific textField 
         if textField == costTextField {
             let textArray = resultString.components(separatedBy: ".")
             if textArray.count > 2 { //Allow only one "."
                return false
             }
           if textArray.count == 2 {
              let lastString = textArray.last
             if lastString!.count > 2 { //Check number of decimal places 
                   return false
               }
            }
          }
           return true
       }
Run Code Online (Sandbox Code Playgroud)