我正在尝试制作类似于spotify登录屏幕的内容。当用户名或密码字段为空时,登录按钮被禁用且无法按下。我不确定如何一致地检查字段是否为空,所以我尝试使用textFieldDidEndEditing,尽管它当前不工作。这就是我到目前为止所拥有的。有没有更有效的方法来解决这个问题?
func textFieldDidEndEditing(textField: UITextField) {
if (usernameField.text! == "" || passwordField.text! == "") {
loginButton.userInteractionEnabled = false
loginButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
print("field empty")
}
}
此外,这里有截图,以供最终目标的参考。
(ps,对不起照片的大小,我不知道如何缩小照片)
答案 0 :(得分:0)
您可以收听文字字段 editingChanged
事件而不是didEndEditing
@IBAction func editingChanged(sender: AnyObject) {
if usernameField.text != "" && passwordField.text != "" {
loginButton.enabled = true
} else {
loginButton.enabled = false
}
}
然后通过代码或界面构建器将两个textField editingChanged
连接起来。
答案 1 :(得分:0)
默认情况下禁用您的登录按钮,因为当登录屏幕出现时文本字段为空...
并实现以下textfield的委托方法:
夫特
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == usernameField {
loginButton.enabled = ((textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string).characters.count > 0 && passwordField.text?.characters.count > 0)
} else if textField == passwordField {
loginButton.enabled = ((textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string).characters.count > 0 && usernameField.text?.characters.count > 0)
}
return true
}
ObjC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.usernameField) {
self.loginButton.enabled = ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 0 && self.passwordField.text.length > 0);
} else if (textField == self.passwordField) {
self.loginButton.enabled = ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 0 && self.usernameField.text.length > 0);
}
return YES;
}
答案 2 :(得分:-1)
我能够通过动物帮助解决问题。只需使用密码字段创建一个新的IBAction并添加以下代码即可轻松解决此问题:
@IBAction func passwordEditing(sender: AnyObject) {
if self.usernameField.text! != "" && self.passwordField.text! != ""{
loginButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
loginButton.userInteractionEnabled = true
print("both fields ok!")
} else {
loginButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
}
}