2016-10-01 66 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 
} 
相關問題