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

后端 未结 3 631
庸人自扰
庸人自扰 2021-01-26 03:12

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

相关标签:
3条回答
  • 2021-01-26 03:49
    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
        }
    }
    
    0 讨论(0)
  • 2021-01-26 03:52

    Try this in textViewDidChange method:

    yourBarButtonItem.isEnabled = !(yourTextField.text?.isEmpty ?? false)
    
    0 讨论(0)
  • 2021-01-26 04:02

    Try to use another delegate method for you're purpose. This is example :

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var button: UIButton!
        @IBOutlet weak var textView: UITextView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            textView.delegate = self
    
            if (textView.text.isEmpty) {
                button.enabled = false
            }
        }
    }
    
    extension ViewController: UITextViewDelegate {
    
        func textView(textView: UITextView, range: NSRange, replacementText text: String) -> Bool
        {
            if (!textView.text.isEmpty) {
                button.enabled = true
            } else {
                 button.enabled = false
            }
            return true
        }
    }
    
    0 讨论(0)
提交回复
热议问题