How do I turn a login button on and off on Swift?

Asked

Viewed 42 times

0

I am creating a login screen, I want: in case the user has not entered your document (username) the login button is disabled.

import UIKit

class loginManager: UIViewController, UITextFieldDelegate {

        @IBOutlet weak var document: UITextField!
        @IBOutlet weak var loginButton: UIButton!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            document.delegate = self
            loginButton.isEnabled = false
        }
    }
    extension ViewController: UITextFieldDelegate {
        
        extension ViewController: UITextFieldDelegate {
            func documentDidEndEditing(_ document: UITextField) {
                if document.text?.isEmpty == false {
                    loginButton.isEnabled = true
                } else {
                    loginButton.isEnabled = false
                }
            }
        }
    }

2 answers

0


Hello @YAGOCOMY, the problem with your implementation is that you have included an extension within another:

import UIKit

class LoginManagerViewController: UIViewController {

  @IBOutlet weak var document: UITextField!
  @IBOutlet weak var loginButton: UIButton!

  override func viewDidLoad() {
    super.viewDidLoad()
    
    document.delegate = self
    loginButton.isEnabled = false
  }
}

extension LoginManagerViewController: UITextFieldDelegate {
  func documentDidEndEditing(_ document: UITextField) {
    if document.text?.isEmpty == false {
        loginButton.isEnabled = true
    } else {
        loginButton.isEnabled = false
    }
  }
}

0

As extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend the types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions have no names.)

Extensions on Swift can:

  • Add computed instance properties and computed type properties
  • Define instance methods and type methods
  • Provides new initializers
  • Define subscriptions
  • Define and use new nested types
  • Make an existing type in accordance with a protocol

You can use it this way:

class LoginManagerViewController: UIViewController, UITextFieldDelegate {

}

or in this way:

class LoginManagerViewController: UIViewController {
    ....
}
extension LoginManagerViewController: UITextFieldDelegate {
   
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.