Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable a button if a text field is empty?

Tags:

ios

swift

I'm trying to disable the continue button if there is nothing in the text field. Here's my code...

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var nounTextField: UITextField!
@IBOutlet weak var `continue`: UIButton!

var noun = String()

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func continueButton(sender: AnyObject) {
    noun = nounTextField.text!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let nvc = segue.destinationViewController as! ViewController2
    nvc.noun2 = noun
} 
}
like image 373
Johnd Avatar asked Dec 03 '22 15:12

Johnd


2 Answers

since you've already made your class a UITextFieldDelegate ad this function

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

    if !text.isEmpty{
        continueButton.userInteractionEnabled = true 
    } else {
        continueButton.userInteractionEnabled = false 
    } 
    return true
}

also update your viewDidLoad function

override func viewDidLoad() {
    super.viewDidLoad()

    nounTextField.delegate = self
    if nounTextField.text.isEmpty{
        continueButton.userInteractionEnabled = false 
    }
}
like image 183
Steve Avatar answered Dec 08 '22 00:12

Steve


Swift 5 version

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    guard let oldText = textField.text else {
        return false
    }
    
    let newText = (oldText as NSString).replacingCharacters(in: range, with: string)
    continueButton.isEnabled = !newText.isEmpty
    return true
}
like image 40
Mahendra Avatar answered Dec 08 '22 00:12

Mahendra