Tejal Ohara
Tejal Ohara

Reputation: 17

UIbutton background colour and button enable/disable

How can we set a hex value to the background of button value is #88D317? Also, I want to keep the button enabled only if there is text present in textfields, else disabled.

Here is the code I have written:

class ViewControllerDonarLogin: UIViewController, UITextFieldDelegate {
    @IBOutlet var btnlogin: UIButton!
    @IBOutlet weak var btn: UIButton!
    @IBOutlet weak var textfieldpassword: UITextField!
    @IBOutlet weak var textfieldusername: UITextField!

    var alert : UIAlertController = UIAlertController()
    var action : UIAlertAction = UIAlertAction()

    override func viewDidLoad() {
        super.viewDidLoad()

        buttonborder()

        btnlogin.backgroundColor = UIColor(red: 136/255, green: 211/255, blue: 23/255, alpha: 0.5)

        if textfieldpassword.text == "" && textfieldusername.text == "" {
            btnlogin.isEnabled = false
        } else {
            btnlogin.isEnabled = true
        }
        // Do any additional setup after loading the view.
    }
}

Upvotes: 0

Views: 41

Answers (2)

Kadian
Kadian

Reputation: 654

What you want to achieve can be done by using text field delegates. You will have to use

func textFieldDidEndEditing(_ textField: UITextField) {
     if textfieldpassword.text == "" || textfieldusername.text == "" {
        btnlogin.isEnabled = false
    } else {
        btnlogin.isEnabled = true
    }
}

also you will have to disable the button in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    btnlogin.isEnabled = false // as you want button to be disabled at the starting 
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 274520

You can use one of the text field's UIControl actions.

In viewDidLoad, add self as a target for editingChanged:

textfieldpassword.addTarget(self, action: #selector(textChanged), for: .editingChanged)
textfieldusername.addTarget(self, action: #selector(textChanged), for: .editingChanged)

Now, add this method:

func textChanged() {
    // This will be called every time the text field's text changes
}

Move the original code you wrote in viewDidLoad to the above method.

if textfieldpassword.text == "" || textfieldusername.text == ""
{
    btnlogin.isEnabled = false
}
else
{
    btnlogin.isEnabled = true
}

Upvotes: 1

Related Questions