【发布时间】:2019-11-03 05:35:46
【问题描述】:
我有 2 个UITextField 和一个自定义的UIButton。我检查UITextField 和enable 按钮是否都有值。如果用户返回并删除其中任何一个中的值,则按钮状态将返回到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
}
我做错了什么?
【问题讨论】:
-
你在哪里调用 authButton()?
-
在
viewWillLayoutSubviews() -
authButton 是 uibutton 子类中的一个函数
-
是的,
Login按钮是UIButton,authButton是extension的UIButton。所以我打电话给loginButton.authButton()viewWillLayoutSubviews()