Swift_監聽UITextField內容的變化

weixin_34320159發表於2016-08-17

今天開發APP的過程中,發現了一個問題,在記住密碼的前提下,如果我清空賬號,密碼和記住密碼的勾選框也需要清空,好了,廢話不多說,直接上圖,大家就明白了:

1708203-c0805747bcb1723c.png
Paste_Image.png
解決方法:

1. 給文字框新增一個方法,注意,forControlEvents設定成EditingChanged

 userNameTextField.addTarget(self, action: Selector("clearPasswordTextFieldAndRememberPwd:"), forControlEvents: .EditingChanged)

2. 實現方法

    func clearPasswordTextFieldAndRememberPwd(textField: UITextField) {
        if rememberPwd {
            self.rememberPwd = !self.rememberPwd
            updateRemPwdCheckbox()
            passwordTextField.text = ""
        }
    }
    func updateRemPwdCheckbox() {
        if rememberPwd == true {
            remPwdCheckbox.setImage(UIImage(named: "checkbox"), forState: .Normal)
        } else {
            passwordTextField.text = ""
            NSUserDefaults.standardUserDefaults().setBool(rememberPwd, forKey: "rememberPwdEnabled")
            encryptedPwd = false
            remPwdCheckbox.setImage(UIImage(named: "checkbox_n"), forState: .Normal)
        }
    }

相關文章