我正在努力用Swift 3做这个。我有一个文本字段,我想限制只有数字和一个小数点和小数点后的两个字符。我还想让它在输入非整数时不使用小数点的区域中工作。谢谢你的任何建议!
答案 0 :(得分:1)
您需要将委托分配给您的文本字段,并在shouldChangeCharactersIn委托方法中进行验证:
使用字符串验证方法添加扩展名:
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
}
}
在您的委托方法中:
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
}