更改自定义UIButton状态时的UI问题

时间:2019-06-20 11:45:57

标签: ios swift uibutton

我有2个UITextField和一个自定义UIButton。我先检查UITextFieldenable这两个按钮中是否都有值。如果用户返回并删除其中任何一个的值,则按钮状态将返回到disabled。我的问题是用户界面。启用时-按钮的标题应为白色,紫色,而禁用时,按钮的颜色应为清澈(作为背景色),标题和边框的颜色应为浅灰色。这是该UIButton的方法:

func authButton() {
    layer.cornerRadius = 5
    layer.borderWidth = 1
    clipsToBounds = true
    if state ==  .normal {
        layer.borderColor = UIColor.white.cgColor
        backgroundColor = UIColor.white
        setTitleColor(Colors.purpleDarker, for: .normal)
    }
    else if state == .disabled {
        layer.borderColor = UIColor.lightText.cgColor
        backgroundColor = UIColor.gray
        setTitleColor(.lightText, for: .disabled)
    }
}

工作正常,直到用户从文本字段中删除内容,然后背景保持白色并且标题类别为“消失”(或其不可见)。仅当用户点击关键字上的“完成”按钮,然后将状态更改为“禁用”时,它才起作用。

这是我在UITextField中检查这些更改的方式(两个文本字段均设置了代理):

func handleTextFields() {
    emailTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
    passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
}

@objc func textFieldDidChange() {
    print("11111")
    guard let email = emailTextField.text, !email.isEmpty,
          let pass = passwordTextField.text, !pass.isEmpty
    else {
        loginButton.isEnabled = false
        return
    }
    loginButton.isEnabled = true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    switch textField {
    case emailTextField:
        passwordTextField.becomeFirstResponder()
    case passwordTextField:
        passwordTextField.resignFirstResponder()
    default:
        break
    }
    return true
}

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

根据您的评论...

移动:

loginButton.authButton()

viewWillLayoutSubviews()viewDidLoad(),然后将textFieldDidChange()函数更改为:

@objc func textFieldDidChange() {
    print("11111")
    guard let email = emailTextField.text, !email.isEmpty,
          let pass = passwordTextField.text, !pass.isEmpty
    else {
        loginButton.isEnabled = false
        // update your customized "state"
        loginButton.authButton()
        return
    }
    loginButton.isEnabled = true
    // update your customized "state"
    loginButton.authButton()
}

答案 1 :(得分:0)

尝试此操作可能会有所帮助,而无需在viewWillLayoutSubviews中调用authButton()

extension UIButton {
    open override func draw(_ rect: CGRect) {
        authButton()
    }
    func authButton() {
        layer.cornerRadius = 5
        layer.borderWidth = 1
        clipsToBounds = true
        if state ==  .normal {
            layer.borderColor = UIColor.white.cgColor
            backgroundColor = UIColor.white
            setTitleColor(.red, for: .normal)
        }
        else if state == .disabled {
            layer.borderColor = UIColor.lightText.cgColor
            backgroundColor = UIColor.yellow
            setTitleColor(.yellow, for: .disabled)
        }
    }
}