如何将文本框条目限制在swift 4中的2个小数位?
答
设置你的控制器为代表的文本字段,并检查提议的字符串满足您的要求:
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
}
答
伙计们,这里的解决方案:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let dotString = "."
if let text = textField.text {
let isDeleteKey = string.isEmpty
if !isDeleteKey {
if text.contains(dotString) {
if text.components(separatedBy: dotString)[1].count == 2 {
return false
}
}
}
}
}
使用'UITextFieldDelegate'” s'shouldChangeCharactersIn' +将小数点转到X位置 – nathan