Search code examples
swiftios9

the button is disabled when text view is empty else is enabled


I'm developing note app, when the text view is empty the done button should be disabled so user could not be able to save empty notes into data base, else the button should be enabled.

here's my code below, my attempts have failed; how I can solve this problem?

 @IBOutlet weak var textView: UITextView!
 @IBOutlet weak var done: UIBarButtonItem!

 override func viewDidLoad() {
        super.viewDidLoad()

        title = note?.text
        if (self.textView.text.isEmpty){
            done.enabled = false
        }
        if let noteContent = note

        {
            textView.text = noteContent.text
        }

         self.navigationController!.toolbarHidden = false;
    }

  func textViewShouldBeginEditing(textView: UITextView) -> Bool{
done.enabled = true

    return done.enabled
}

Solution

    1. Make your view controller conform to UITextViewDelegate protocol
    2. In Interface Builder, connect the delegate on the text view to your view controller.
    3. Add the following function to your view controller:

    func textViewDidChange(textView: UITextView) {
        if textView == self.textView {
            self.doneButton.enabled = !textView.text.isEmpty
        }
    }