Reputation: 597
How I can apply some actions when user/developer set value for "text" property (UITextField object) in code or in storyboard. How I can detect changing core property?
Upvotes: 1
Views: 4341
Reputation: 87
In swift...
textField.addTarget(self, action: #selector(textDidChange(_:)), for: .editingChanged)
@objc func textDidChange(_ textField: UITextField) {
// DO something with textField.text
}
Upvotes: 0
Reputation: 12915
The simplest way is:
override public var text : String? {
didSet {
// Do whatever you want, for example
if !(text != nil && text!.isEmpty) {
}
}
}
Upvotes: 7
Reputation: 10286
You can add an observer for key path text to your textfield than implement observeValueForKeyPath method
override func viewDidLoad() {
super.viewDidLoad()
myTextField.addObserver(self, forKeyPath: "text", options: .New, context: nil)
// Do any additional setup after loading the view.
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
let newText = change[NSKeyValueChangeNewKey] as String
// add your action here
}
deinit{
myTextField.removeObserver(self, forKeyPath: "text")
}
Upvotes: 3
Reputation: 236340
You just have to create an Outlet for your textfield and a IBAction for Sent Events Editing Changed.
@IBOutlet weak var strText: UITextField!
@IBAction func editedAction(sender: AnyObject) {
// do whatever
// strText.text = "whatever"
}
Upvotes: 0