本文介绍了将文本字段限制为一个小数点输入,仅数字和小数点后两个字符-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力使用Swift 3做到这一点.我有一个文本字段,我想限制为仅数字,小数点和小数点后两个字符.我还希望它在输入非整数时不使用小数点的区域中起作用.谢谢您的任何建议!
I am struggling to do this with Swift 3. I have a text field that I would like to limit to only numbers and one decimal point and two characters after the decimal place. I would also like to have it work in regions where a decimal point is not used when entering non-integers. Thank you for any suggestions!
推荐答案
您需要将委托分配给您的文本字段,并在shouldChangeCharactersIn委托方法中进行验证:
You need to assign delegate to your textfield and in the shouldChangeCharactersIn delegate method do your validations:
-
为字符串添加带有验证方法的扩展名:
Add extension with validation methods for the string:
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
}
}
在您的委托方法中:
In your delegate method:
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)
}
这篇关于将文本字段限制为一个小数点输入,仅数字和小数点后两个字符-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!