Reputation: 167
I'm trying to grey out a UIBarButtonItem when the TextView is empty, and enable it when the TextView isn't empty.
class ViewController: UIViewController {
@IBOutlet weak var text: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let newButton = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: nil)
toolbarItems = [newButton]
navigationController?.isToolbarHidden = false
}
I have heard suggestion about implementing an observer or implementing a TextView delegate method. Can someone please provide a concrete example.
Thank you so much.
Upvotes: 0
Views: 124
Reputation: 213
Please try my code.
I used it for my project.
func textChanged(sender: NSNotification) {
if emailTextField.hasText && passwordTextField.hasText {
loginButton.isEnabled = true
loginButton.backgroundColor = UIColor(r: 139, g: 0, b: 139)
} else {
loginButton.backgroundColor = UIColor(r: 139, g: 77, b: 139)
loginButton.isEnabled = false
}
}
and add this to viewDidload:
NotificationCenter.default.addObserver(self,selector: #selector(textChanged),name:NSNotification.Name.UITextFieldTextDidChange,object: nil)
loginButton.isEnabled = false
Upvotes: 3