2016-10-01 38 views

回答

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) 
    
    } 
    
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 
} 
相关问题