How do I go about allowing my login button to be clicked only if the username and password text fields have been filled in?
Ideally the login button would be grayed out and un-clickable, only becoming fully functional once all fields have been filled in.
I'm very new to iOS development, so I am also unsure if I'd need to do anything regarding the "UITextFieldDelegate", would that be an important aspect here?
import UIKit
class LoginController: UIViewController {
// Creating text fields
let emailTF: UITextField = {
let e = UITextField()
let attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
e.attributedPlaceholder = attributedPlaceholder
e.textColor = .white
e.keyboardType = UIKeyboardType.emailAddress
e.setBottomBorder(backgroundColor: ORANGE_COLOR, borderColor: .white)
return e
}()
let passwordTF: UITextField = {
let p = UITextField()
let attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
p.attributedPlaceholder = attributedPlaceholder
p.textColor = .white
p.setBottomBorder(backgroundColor: ORANGE_COLOR, borderColor: .white)
p.isSecureTextEntry = true
return p
}()
// Creating buttons
let loginButton: UIButton = {
let l = UIButton(type: .system)
l.setTitleColor(.white, for: .normal)
l.setTitle("Log In", for: .normal)
l.backgroundColor = UIColor.rgb(r: 89, g: 156, b: 120)
l.layer.cornerRadius = 25
return l
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
view.backgroundColor = ORANGE_COLOR
setupTextFields()
setupLoginButton()
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
// Text Field Setup Functions
fileprivate func setupTextFields() {
setupEmailTF()
setupPasswordTF()
}
fileprivate func setupEmailTF() {
view.addSubview(emailTF)
emailTF.anchors(top: nil, topPad: 0, bottom: nil, bottomPad: 0, left: view.leftAnchor, leftPad: 24, right: view.rightAnchor, rightPad: 24, height: 30, width: nil)
emailTF.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
fileprivate func setupPasswordTF() {
view.addSubview(passwordTF)
passwordTF.anchors(top: emailTF.bottomAnchor, topPad: CGFloat(TEXT_FIELD_SPACING), bottom: nil, bottomPad: 0, left: emailTF.leftAnchor, leftPad: 0, right: emailTF.rightAnchor, rightPad: 0, height: 30, width: nil)
}
// Button Setup Functions
fileprivate func setupLoginButton() {
view.addSubview(loginButton)
loginButton.anchors(top: passwordTF.bottomAnchor, topPad: CGFloat(TEXT_FIELD_SPACING * 2), bottom: nil, bottomPad: 0, left: passwordTF.leftAnchor, leftPad: 0, right: passwordTF.rightAnchor, rightPad: 0, height: 50, width: nil)
}
}