Swift.10行代碼為TextField添加金額輸入限制

實(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

有問題歡迎探討.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容