将文本字段限制为一个小数点输入,仅限数字,以及小数位后的两个字符 - Swift 3

时间:2016-10-01 13:47:29

标签: ios swift swift3

我正在努力用Swift 3做这个。我有一个文本字段,我想限制只有数字和一个小数点和小数点后的两个字符。我还想让它在输入非整数时不使用小数点的区域中工作。谢谢你的任何建议!

2 个答案:

答案 0 :(得分:1)

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

  1. 使用字符串验证方法添加扩展名:

    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)
    
    }
    

答案 1 :(得分:0)

 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
}