UITextField 輸入小數
·
2min
前言
如何檢測 UITextField 輸入小數.
實作
- 設置 textField.keyboardType = .decimalPad
- 設置 textField.delegate = ...
- 處理 delegate functions shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
/// 1.过滤删除事件
guard !string.isEmpty else {
return true
}
/// 2.检查允许输入的合法字符
guard "0123456789.".contains(string) else {
return false
}
/// 3.检查总长度限制 (最多输入10位)
if text.count >= 10 {
return false
}
/// 4.检查小数点后位数限制 (小数点后最多输入2位)
if let ran = text.range(of: "."), range.location - NSRange(ran, in: text).location > 2 {
return false
}
/// 5.检查首位输入是否为0
if text == "0", string != "." {
textField.text = string
return false
}
/// 6.特殊情况检查
guard string == "." || string == "0" else {
return true
}
/// a.首位小数点替换为0.
if text.count == 0, string == "." {
textField.text = "0."
return false
}
/// b.禁止多次输入小数点
if text.range(of: ".") != nil, string == "." {
return false
}
return true
}