實(shí)現(xiàn)效果:
通過textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 代理方法對(duì)textField輸入內(nèi)容進(jìn)行限制,保證只能輸入有效金額。
實(shí)現(xiàn)思路:
首先設(shè)置TextField的keyboardType為.decimalPad,只能輸入數(shù)字與小數(shù)點(diǎn)。之后在代理方法中,對(duì)輸入字符為"."和"0"兩種情況進(jìn)行限制。
完整代碼
let textField: UITextField = {
let textField = UITextField(frame: CGRect(x: 100, y: 200, width: 200, height: 50))
textField.keyboardType = .decimalPad
return textField
}()
extension ViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard string == "." || string == "0" else { return true }
guard let text = textField.text else { return true }
if text.count == 0 {
textField.text = "0."
return false
}
if text.range(of: ".") != nil && string == "." {
return false
}
return true
}
}
demo地址: EWNumberTextField
有問題歡迎探討.