ios - 如何改进 Swift / Xcode iOS App 中文本字段的控制语句?
问题描述
我正在为 iPhone 设置一个新应用程序,并且我只想在文本字段不为空时将用户输入信息添加到我的数据库中。
有 4 个文本字段,但只需完成一个即可更新我的数据库。
Swift 和 iOS 编码对我来说是新的。
这是我要改进的代码:
@IBAction func confirmButtonWasPressed(_ sender: UIButton) {
print("Redirection to confirmation screen.")
if confirmpasswordTextField.text != "" {
print("Updating informations.")
// Read values from text fields
let userName = newusernameTextField.text
let userMail = newmailTextField.text
let userPhone = newphoneTextField.text
let userPassword = newpasswordTextField.text
if userName?.isEmpty ?? true {
print("textField is empty")
} else {
print("textField has some text")
}
if userMail?.isEmpty ?? true {
print("textField is empty")
} else {
print("textField has some text")
}
if userPhone?.isEmpty ?? true {
print("textField is empty")
} else {
print("textField has some text")
}
if userPassword?.isEmpty ?? true {
print("textField is empty")
} else {
print("textField has some text")
}
}else{
print("Error: Please enter your password.")
}
}
如果有的话,我想减少这个功能并获得输入。
我可以用这段代码做到这一点,但我相信有一个捷径可以做到这一点。
谢谢。
解决方案
extension String {
public var isBlank: Bool {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
}
@IBAction func confirmButtonWasPressed(_ sender: UIButton) {
validateLogin()
}
func validateLogin(){
guard let username = userNameTextfield.text, !username.isBlank else {
return
}
guard let password = passwordTextField.text, !password.isBlank else {
return
}
}