how to add an action on UITextField return key?

IosObjective CIphoneSwiftUitextfield

Ios Problem Overview


I have a button and text textfield in my view. when i click on the textfield a keyboard appears and i can write on the textfield and i also able to dismiss the keyboard by clicking on the button by adding:

[self.inputText resignFirstResponder];

Now I want to enable return key of keyboard. when i will press on the keyboard keyboard will disappear and something will happen. How can I do this?

Ios Solutions


Solution 1 - Ios

Ensure "self" subscribes to UITextFieldDelegate and initialise inputText with:

self.inputText.delegate = self;

Add the following method to "self":

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.inputText) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

Or in Swift:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if textField == inputText {
        textField.resignFirstResponder()
        return false
    }
    return true
}

Solution 2 - Ios

With extension style in swift 3.0

First, set up delegate for your text field.

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

Then conform to UITextFieldDelegate in your view controller's extension

extension YourViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == inputText {
            textField.resignFirstResponder()
            return false
        }
        return true
    }
}

Solution 3 - Ios

While the other answers work correctly, I prefer doing the following:

In viewDidLoad(), add

self.textField.addTarget(self, action: #selector(onReturn), for: UIControl.Event.editingDidEndOnExit)

and define the function

@IBAction func onReturn() {
    self.textField.resignFirstResponder()
    // do whatever you want...
}

Solution 4 - Ios

Use Target-Action UIKit mechanism for "primaryActionTriggered" UIEvent sent from UITextField when a keyboard done button is tapped.

textField.addTarget(self, action: Selector("actionMethodName"), for: .primaryActionTriggered)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrazibdebView Question on Stackoverflow
Solution 1 - IosAnderView Answer on Stackoverflow
Solution 2 - IosFangmingView Answer on Stackoverflow
Solution 3 - IosMalfunctionView Answer on Stackoverflow
Solution 4 - IosBlazej SLEBODAView Answer on Stackoverflow