如何在swift 4中将文本字段输入限制为2位小数?
问题描述:
我有一个文本字段,我想将条目限制为最多2位小数。
I have a textfield and I want to limit the entry to max 2 decimal places.
允许12.34之类的号码,但不允许12.345
number like 12.34 is allowed but not 12.345
我该怎么做?
答
将控制器设置为文本字段的委托,并检查建议的字符串是否满足您的要求:
Set your controller as the delegate for the text field and check if the proposed string satisfy your requirements:
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
textField.keyboardType = .decimalPad
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let r = Range(range, in: oldText) else {
return true
}
let newText = oldText.replacingCharacters(in: r, with: string)
let isNumeric = newText.isEmpty || (Double(newText) != nil)
let numberOfDots = newText.components(separatedBy: ".").count - 1
let numberOfDecimalDigits: Int
if let dotIndex = newText.index(of: ".") {
numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
} else {
numberOfDecimalDigits = 0
}
return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
}