Artem Krachulov
Artem Krachulov

Reputation: 597

UITextField "text" property setter in Swift

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

Answers (4)

coreyd303
coreyd303

Reputation: 87

In swift...

textField.addTarget(self, action: #selector(textDidChange(_:)), for: .editingChanged)

 @objc func textDidChange(_ textField: UITextField) {
     // DO something with textField.text
 }

Upvotes: 0

Bagusflyer
Bagusflyer

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

Zell B.
Zell B.

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

Leo Dabus
Leo Dabus

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"
}

enter image description here

Upvotes: 0

Related Questions