Disable/enable 基于 UITextView 内容的 UIBarButtonItem swift
Disable/enable UIBarButtonItem base on UITextView content swift
我试图在 TextView 为空时使 UIBarButtonItem 变灰,并在 TextView 不为空时启用它。
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
}
我听说过有关实施观察者或实施 TextView 委托方法的建议。有人可以提供一个具体的例子。
非常感谢。
请试试我的代码。
我将它用于我的项目。
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
}
}
并将其添加到 viewDidload:
NotificationCenter.default.addObserver(self,selector: #selector(textChanged),name:NSNotification.Name.UITextFieldTextDidChange,object: nil)
loginButton.isEnabled = false
我试图在 TextView 为空时使 UIBarButtonItem 变灰,并在 TextView 不为空时启用它。
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
}
我听说过有关实施观察者或实施 TextView 委托方法的建议。有人可以提供一个具体的例子。
非常感谢。
请试试我的代码。
我将它用于我的项目。
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
}
}
并将其添加到 viewDidload:
NotificationCenter.default.addObserver(self,selector: #selector(textChanged),name:NSNotification.Name.UITextFieldTextDidChange,object: nil)
loginButton.isEnabled = false