将文本字段限制为一个小数点input,仅限数字,小数点后两个字符 – Swift 3

我正在努力与Swift 3做到这一点。我有一个文本字段,我想限制在小数点后面只有数字和一个小数点和两个字符。 我也想在input非整数时在没有使用小数点的地区使用它。 谢谢你的任何build议!

您需要将委托分配到您的文本字段,并在shouldChangeCharactersIn委托方法中进行validation:

  1. 添加扩展与string的validation方法:

    extension String{ private static let decimalFormatter:NumberFormatter = { let formatter = NumberFormatter() formatter.allowsFloats = true return formatter }() private var decimalSeparator:String{ return String.decimalFormatter.decimalSeparator ?? "." } func isValidDecimal(maximumFractionDigits:Int)->Bool{ // Depends on you if you consider empty string as valid number guard self.isEmpty == false else { return true } // Check if valid decimal if let _ = String.decimalFormatter.number(from: self){ // Get fraction digits part using separator let numberComponents = self.components(separatedBy: decimalSeparator) let fractionDigits = numberComponents.count == 2 ? numberComponents.last ?? "" : "" return fractionDigits.characters.count <= maximumFractionDigits } return false } } 
  2. 在你的委托方法中:

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Get text let currentText = textField.text ?? "" let replacementText = (currentText as NSString).replacingCharacters(in: range, with: string) // Validate return replacementText.isValidDecimal(maximumFractionDigits: 2) } 
  var number = Double(yourTextfield.text) if number != nil { //if user enters more than 2 digits after the decimal point it will round it up to 2 let roundedNumber = Double(num!).roundTo(places: 2) } else { //probably print an error message }