shanemarvinmay
shanemarvinmay

Reputation: 53

How to trigger function when press "Enter" on keyboard

How may I trigger the button callback function of the test function when the user presses "Enter" on the phone's keyboard?

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var textfield: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textfield.delegate = self 
    }

    @IBAction func btn(_ sender: Any) {
        //textfield.resignFirstResponder()
        label.text = textfield.text!
        print("\n func completed \n")
    }

    func test(textField: UITextField!) {
        textfield.resignFirstResponder()
        print("\n func completed \n")
    }
}

Upvotes: 0

Views: 1101

Answers (2)

AamirR
AamirR

Reputation: 12208

You can add target to handle the specific events, as such:

textField.addTarget(self, action: #selector(editingDidEnd), for: .editingDidEndOnExit)


@objc func editingDidEnd() {
    // Do whatever you would like here, in your case
    self.btnCallback()
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100533

You can try it directly

func textFieldShouldReturn(_ textField: UITextField) -> Bool {    
   textField.resignFirstResponder() // options 1
   self.test(textField)  // option 2
   self.calledFromAnyWhere() // option 3  
   return true
}

Edit: If you want to call the button's action it's preferred to make a shared function

 @IBAction func btn(_ sender: Any) {

   self.calledFromAnyWhere()
}

func calledFromAnyWhere()
{
    // any content
}

Upvotes: 2

Related Questions