2

Hi i'm new with Swift programming. What im trying to do is Disable my button (signIn) in viewDidLoad and only enable when the textfields have text in them. Here's what i've achieved so far. (not much though!)

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    signIn.isEnabled = false

    // Do any additional setup after loading the view, typically from a nib.
}

@IBOutlet weak var emailtxt: UITextField!
@IBOutlet weak var passwordtxt: UITextField!
@IBOutlet weak var signIn: UIButton!

I need help to create a function in signIn that keeps button disabled until text fields (emailtxt & passwordtxt) have text in them and then proceed.

Glad if anyone can sort me. Thanks in advance!

6
  • Have you used any cocoapods before. I can tell you better library to do it for you and right way Commented Apr 29, 2018 at 5:18
  • You must create an action by dragging your inputs into your ViewController, and in this function check if all input texts aren't equals nil
    – Treast
    Commented Apr 29, 2018 at 5:19
  • @VeerSuthar ..Would love to try it. I have cocoapods enabled. Let me know
    – Roger
    Commented Apr 29, 2018 at 5:21
  • @Treast you meant to create an IBAction for SignIn and have a function check on textfields= nil? But I want my button to be disabled onviewload. Im not able to achieve disable button with IBAction, hence chose it as an Outlet.
    – Roger
    Commented Apr 29, 2018 at 5:25
  • Oh ok, have you tried to put your Outlets at the begining of the ViewController ?
    – Treast
    Commented Apr 29, 2018 at 5:28

4 Answers 4

3

First add these for all of your textFields in viewDidLoad():

    emailtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
                        for: UIControlEvents.editingChanged)
   passwordtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
                        for: UIControlEvents.editingChanged)

Then use this:

@objc func textFieldDidChange(_ textField: UITextField) {
    self.buttonIsEnabled()
}

func buttonIsEnabled() {
    var buttonIsEnabled = true

    defer {
        self.signIn.isEnabled = buttonIsEnabled
    }

    guard let emailtxt = self.emailtxt.text, !emailtxt.isEmpty  else {
        addButtonIsEnabled = false
        return
    }


    guard let passwordtxt = self. passwordtxt.text, ! passwordtxt.isEmpty  else {
        addButtonIsEnabled = false
        return
    }

}

I use this way in my codes and it works well.

Even you can add more methods for additional checking to buttonIsEnabled, like:

self.checkEmailIsValid(for: emailtxt)

Of course you should handle this method before:

 func checkEmailIsValid(for: String) {
   //...
}
2

Set ViewController as delegate for emailtxt and passwordtxt like this,

override func viewDidLoad() {
    super.viewDidLoad()
    signIn.isEnabled = false

    emailtxt.delegate = self
    passwordtxt.delegate = self 

    // Do any additional setup after loading the view, typically from a nib.
}

Conform your ViewController to UITextFieldDelegate and enable/disable as the text input is finished,

extension ViewController: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
            signIn.isEnabled = true
        } else {
            signIn.isEnabled = false
        }
    }
}

Here is the fix for your code you shared.

import UIKit
extension UIViewController {

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

extension SignInVC: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
            signIn.isEnabled = true
        } else {
            signIn.isEnabled = false
        }
    }
}
class SignInVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        signIn.isEnabled = false
        emailtxt.delegate = self
        passwordtxt.delegate = self
        self.hideKeyboardWhenTappedAround()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet weak var emailtxt: UITextField!
    @IBOutlet weak var passwordtxt: UITextField!
    @IBOutlet weak var signIn: UIButton!
}
6
  • Thanks Kamran. Appreciate your response. However, after following your solution, Xcode initially asked me to change func 'textFieldDidEndEditing' into public. Secondly, since ive pasted the extension after import UIKit, i am not getting 'Use of unresolved identifiers for my textfields (emailtxt and passwordtxt) and for signIn button as well. Have i declared the extension at wrong line?
    – Roger
    Commented Apr 29, 2018 at 6:07
  • @user2512126 Yes, i believe you pasted the extension inside the scope of ViewController. You should take the extension out of ViewController scope. Let me know if you can't so i will edit my answer.
    – Kamran
    Commented Apr 29, 2018 at 6:13
  • Im a bit losty here on where to paste it then. Care to walk me through? Ive tried pasting it under import UIKit and before class ViewController: UIViewController, but its not helping. – user2512126 9 mins ago
    – Roger
    Commented Apr 29, 2018 at 7:08
  • I need 20 reps to talk there!!
    – Roger
    Commented Apr 29, 2018 at 9:13
  • Edited your solution to include my source code. Hope it helps
    – Roger
    Commented Apr 29, 2018 at 9:21
1

What I would do is create an IBAction from one of your text fields, and set the event to Editing Changed:

IBAction set to Editing Changed

The code should look like this:

@IBAction func textFieldEditingDidChange(_ sender: UITextField) {

}

You can then connect that same outlet to both of your text fields by dragging from the outlet to your remaining field. If you've connected both correctly, clicking on the circle to the left of your IBAction should show two text fields:

The action will now be fired every time text changes in either of your fields.

Then, at the top of the file, I'd create a computed property that returns false unless there is something in both fields:

var shouldEnableButton: Bool {
    guard let text1 = textField1.text, let text2 = textField2.text else {
        return false
    }
    return text1.isEmpty && text2.isEmpty ? false : true
}

Finally, we add shouldEnableButton to our IBAction:

@IBAction func textFieldEditingDidChange(_ sender: UITextField) {
    button.isEnabled = shouldEnableButton
}

Important

When you connect your second text field to the outlet, it will incorrectly assign Editing Did End as its event:

Delete this event and click and drag from Editing Changed to your IBAction:

0

Use SwiftValidator

https://github.com/SwiftValidatorCommunity/SwiftValidator

by this, you will set validation of email & password like below

import SwiftValidator

let validator = Validator()

validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])




// MARK: - ValidationDelegate
extension ViewController: ValidationDelegate {
    func validationSuccessful() {
        self.loginUser()
    }

    func validationFailed(_ errors:[(Validatable ,ValidationError)]) {
        for (field, error) in errors {

//Handle as per need - show extra label - shake view etc
/*
            if let field = field as? UITextField {
                Utilities.shakeTheView(shakeView: field)
            }
            error.errorLabel?.text = error.errorMessage
            error.errorLabel?.isHidden = false
*/
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.