How to Handle IQKeyboardManager Done button action in toolbar? - ios

I am new in ios I work on iqkeyboardmanager and I want to access Done button action in IQKeyboardManager.

You can handle clicks of done, next and previous button
[textField.keyboardToolbar.previousBarButton setTarget:self action:#selector(previousAction:)];
[textField.keyboardToolbar.nextBarButton setTarget:self action:#selector(nextAction:)];
[textField.keyboardToolbar.doneBarButton setTarget:self action:#selector(doneAction:)];
In swift:
customField.keyboardToolbar.doneBarButton.setTarget(self, action: #selector(doneButtonClicked))
func doneButtonClicked(_ sender: Any) {
//your code when clicked on done
}

you can use UITextViewDelegate
func textFieldDidEndEditing(_ textField: UITextField) {
}

You can import
import IQKeyboardManager
in required file and after that
vc1Textfield.addDoneOnKeyboard(withTarget: self, action: #selector(doneButtonClicked))
here vc1Textfield is my textfield and doneButtonClicked definition is given below:
#objc func doneButtonClicked(_ sender: Any) { }
Hope it help someone!!! Happy Coding....

I will try to describe in a more convenient way:
import IQKeyboardManagerSwift
class EditPostViewCell: UITableViewCell {
#IBOutlet weak var commentTextView: UITextView!
override func awakeFromNib() {
IQKeyboardManager.shared.toolbarDoneBarButtonItemText = "Send Comment"
commentTextView.delegate = self
}
#objc func didPressOnDoneButton() {
commentTextView.resignFirstResponder()
sendComment()
}
}
extension EditPostViewCell: UITextViewDelegate {
public func textViewDidBeginEditing(_ textView: UITextView) {
let invocation = IQInvocation(self, #selector(didPressOnDoneButton))
textView.keyboardToolbar.doneBarButton.invocation = invocation
}
}

First:
import the IQKeyboardManager.h
Then:
[self.textField.keyboardToolbar.doneBarButton setTarget:self action:#selector(doneAction:)];

xcode 11.
Make Action connection textField with code.
#IBAction func yourName(_ sender: Any){
// Your code
}
Connections inspector screen

Related

how to hide keyboard on text view to return in swift3 [duplicate]

I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
the method resignfirstresponder is not getting in function.
You can make the app dismiss the keyboard using the following function
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
Here is a full example to better illustrate that:
//
// ViewController.swift
//
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var myTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
Code source: http://www.snip2code.com/Snippet/85930/swift-delegate-sample
The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:
// Called on 'Return' pressed. Return false to ignore.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
No Delegate Needed
You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:
#IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
Super simple.
(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)
Add UITextFieldDelegate to the class declaration:
class ViewController: UIViewController, UITextFieldDelegate
Connect the textfield or write it programmatically
#IBOutlet weak var userText: UITextField!
set your view controller as the text fields delegate in view did load:
override func viewDidLoad() {
super.viewDidLoad()
self.userText.delegate = self
}
Add the following function
func textFieldShouldReturn(userText: UITextField!) -> Bool {
userText.resignFirstResponder()
return true;
}
with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.
I hate to add the same function to every UIViewController.
By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".
extension UIViewController: UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)
Simple Swift 3 Solution:
Add this function to your view controllers that feature a text field:
#IBAction func textField(_ sender: AnyObject) {
self.view.endEditing(true);
}
Then open up your assistant editor and ensure both your Main.storyboard is on one side of your view and the desired view controller.swift file is on the other. Click on a text field and then select from the right hand side utilities panel 'Show the Connection Inspector' tab. Control drag from the 'Did End on Exit' to the above function in your swift file. Repeat for any other textfield in that scene and link to the same function.
#RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field's class:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
Substitute your outlet's name for textField.
Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:
#IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
Connect all your text fields for that view controller to that action on the Did End On Exit event of each field.
Here's the Swift 3.0 update to peacetype's comment:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
When the user taps the Done button on the text keyboard, a Did End On Exit event will be generated; at that time, we need to tell the text field to give up control so that the keyboard will go away. In order to do that, we need to add an action method to our controller class.
Select ViewController.swift add the following action method:
#IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}
Select Main.storyboard in the Project Navigator and bring up the connections inspector. Drag from the circle next to Did End On Exit to the yellow View Controller icon in the storyboard and let go. A small pop-up menu will appear containing the name of a single action, the one we just added. Click the textFieldDoneEditing action to select it and that's it.
Swift 3
Add this code below to your VC
//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
return false;
}
Works for me
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)}
then you use this function
func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
Swift
Using optional function from UITextFieldDelegate.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(false)
}
false means that field can be ask to resign. true – force resign.
Make sure that your textField delegate is set to the view controller from which you are writing your textfield related code in.
self.textField.delegate = self
you can put this anywhere but not in a UIButton
func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
return (false)
}
then you can put this code in a button(also for example):
self.view.endEditing(true)
this worked for me
In the view controller you are using:
//suppose you are using the textfield label as this
#IBOutlet weak var emailLabel: UITextField!
#IBOutlet weak var passwordLabel: UITextField!
//then your viewdidload should have the code like this
override func viewDidLoad() {
super.viewDidLoad()
self.emailLabel.delegate = self
self.passwordLabel.delegate = self
}
//then you should implement the func named textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// -- then, further if you want to close the keyboard when pressed somewhere else on the screen you can implement the following method too:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true);
}
you should connect the UITextfied with a delegate of view controller to make this function called
All in One Hide Keyboard and Move View on Keyboard Open: Swift 5
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc func taped(){
self.view.endEditing(true)
}
#objc func KeyboardWillShow(sender: NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
#objc func KeyboardWillHide(sender : NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

iOS/Swift: how to detect touch action on a UITextField

I would like to detect the touch action on a UITextField.
It seems the "Touch Up Inside" action is not fired by touching inside the textfield.
It seems "Touch Up Inside" is not enabled for UITextField, but "Touch Down" works.
So the solution is as follows:
Swift 4.x
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
#objc func myTargetFunction(textField: UITextField) {
print("myTargetFunction")
}
Swift 3.x
myTextField.addTarget(self, action: #selector(myTargetFunction), for: UIControlEvents.touchDown)
#objc func myTargetFunction(textField: UITextField) {
print("myTargetFunction")
}
Swift 4 and higher:
class ViewController: UIViewController, UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
print("You edit myTextField")
}
}
}
This is a delegate function.
here's Swfit:
and you don't need to use the "touchUpInside" just use the delegate methods like so:
Make your View controller a delegate:
class ViewController: UIViewController, UITextFieldDelegate{
func textFieldDidBeginEditing(textField: UITextField) -> Bool {
if textField == myTextField {
return true // myTextField was touched
}
}
Here's the other delegate methods:
protocol UITextFieldDelegate : NSObjectProtocol {
optional func textFieldShouldBeginEditing(textField: UITextField) -> Bool // return NO to disallow editing.
optional func textFieldDidBeginEditing(textField: UITextField) // became first responder
optional func textFieldShouldEndEditing(textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
optional func textFieldDidEndEditing(textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text
optional func textFieldShouldClear(textField: UITextField) -> Bool // called when clear button pressed. return NO to ignore (no notifications)
optional func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
}
from swift docs:
struct UIControlEvents : RawOptionSetType {
init(_ rawValue: UInt)
init(rawValue: UInt)
static var TouchDown: UIControlEvents { get } // on all touch downs
static var TouchDownRepeat: UIControlEvents { get } // on multiple touchdowns (tap count > 1)
static var TouchDragInside: UIControlEvents { get }
static var TouchDragOutside: UIControlEvents { get }
static var TouchDragEnter: UIControlEvents { get }
static var TouchDragExit: UIControlEvents { get }
static var TouchUpInside: UIControlEvents { get }
static var TouchUpOutside: UIControlEvents { get }
static var TouchCancel: UIControlEvents { get }
static var ValueChanged: UIControlEvents { get } // sliders, etc.
static var EditingDidBegin: UIControlEvents { get } // UITextField
static var EditingChanged: UIControlEvents { get }
static var EditingDidEnd: UIControlEvents { get }
static var EditingDidEndOnExit: UIControlEvents { get } // 'return key' ending editing
static var AllTouchEvents: UIControlEvents { get } // for touch events
static var AllEditingEvents: UIControlEvents { get } // for UITextField
static var ApplicationReserved: UIControlEvents { get } // range available for application use
static var SystemReserved: UIControlEvents { get } // range reserved for internal framework use
static var AllEvents: UIControlEvents { get }
}
UITextField doesn't respond to "touchUpInside" see to the right side, you'll find it's acceptable control events
Update For Swift 3
Here is the code for Swift 3:
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
This is the function:
func myTargetFunction() {
print("It works!")
}
I referred to the UIControlEvents documentation from Apple and came up with the following:
First add UITextFieldDelegate to your class then,
textBox.delegate = self
textBox.addTarget(self, action: #selector(TextBoxOn(_:)),for: .editingDidBegin)
textBox.addTarget(self, action: #selector(TextBoxOff(_:)),for: .editingDidEnd)
with the following functions:
func TextBoxOff(_ textField: UITextField) {
code
}
}
func TextBox(_ textField: UITextField) {
code
}
}
For Swift 3.1:
1) Create a gesture recognizer:
let textViewRecognizer = UITapGestureRecognizer()
2) Add a handler to the recognizer:
textViewRecognizer.addTarget(self, action: #selector(tappedTextView(_:)))
3) Add the recognizer to your text view:
textView.addGestureRecognizer(textViewRecognizer)
4) Add the handler to your class:
func tappedTextView(_ sender: UITapGestureRecognizer) {
print("detected tap!")
}
To make this a little clearer these things need to be in place. I used this to make it so if a user entered something in an app of my own's credit textField anything in the debit textField is deleted.
UITextFieldDelegate needs to be declared in the View controller i.e class SecondViewController:
The detector functions func myDebitDetector func myCreditDetector need to be in the ViewController class.
put debit.addTarget and credit.addtarget inside view will appear.
#IBOutlet weak var debit: UITextField! and #IBOutlet weak var credit: UITextField! are textfields on the storyboard and connected to the viewController.
class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var credit: UITextField!
#IBOutlet weak var debit: UITextField!
func myDebitDetector(textfield: UITextField ){
print("using debit")
credit.text = ""
}
func myCreditDetector(textfield: UITextField) {
print("using cedit")
debit.text = ""
}
override func viewWillAppear(animated: Bool) {
debit.addTarget(self, action: "myDebitDetector:", forControlEvents: UIControlEvents.TouchDown)
credit.addTarget(self, action: "myCreditDetector:", forControlEvents: UIControlEvents.TouchDown)
....
}
}
Set the UITextField delegate to your view controller
Obj-C
textField.delegate = self;
Swift
textField.delegate = self
Implement the delegate method
Obj-c
-(void)textField:(UITextField*)textField didBeginEditing {
// User touched textField
}
Swift
func textFieldDidBeginEditing(textField: UITextField!) { //delegate method
}
Swift 3.0 Version:
textFieldClientName.addTarget(self, action: Selector(("myTargetFunction:")), for: UIControlEvents.touchDown)
Swift 4.2.
Try .editingDidEnd instead of .touchDown and delegate.
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .editingDidEnd)
#objc func myTargetFunction(textField: UITextField) {
print("textfield pressed")
}
On xamarin.iOS i easy to use:
YourTextField.WeakDelegate = this;
[...]
[Export("textFieldDidBeginEditing:")]
public void TextViewChanged(UITextField textField)
{
if (YourTextField.Equals(textField))
IsYourTextFileFocused = true;
}
** Swift 4.0 + **
Use custom action like this
YourTextField.addTarget(self, action: #selector(myTargetFunction(_:)), for: .allEditingEvents)
#IBAction private func myTargetFunction(_ sender: Any) {
if let textField = sender as? UITextField {
// get textField here
}
}

Swift: how to use UISwitch to control UITextField to be enabled or disabled with a delegate

In XCode 6.3.2, I have a UITextField:
#IBOutlet weak var uiswitchControlledTextField: UITextField!
I am now using a UISwitch (named mySwitch) to control its enabled or disabled state in the following way:
#IBOutlet weak var mySwitch: UISwitch!
mySwitch.addTarget(self, action: Selector("stateChanged:"), forControlEvents: UIControlEvents.ValueChanged)
//callback below:
func stateChanged(switchState: UISwitch) {
uiswitchControlledTextField.enabled = switchState.on
}
The above works well, however, I am looking to try if it would be possible to create a UITextFieldDelegate to control the above UITextField in the same way. So far, I have the following by implementing textFieldShouldBeginEditing, in which I wish to return false to disable the UITextField, but I don't know how to let the UISwitch dynamically return true or false from textFieldShouldBeginEditing
import Foundation
import UIKit
class SwitchControlledTextFieldDelegate: NSObject, UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return false; //do not show keyboard or cursor
}
}
In ViewController, I try to set
self.uiswitchControlledTextField.delegate = SwitchControlledTextFieldDelegate()
but it does not work as I wished. Any help would be appreciated.
self.uiswitchControlledTextField.delegate = SwitchControlledTextFieldDelegate()
The problem is that that line merely creates an instance of your SwitchControlledTextFieldDelegate class, which then immediately goes right back out of existence.
You need to use, as your text field delegate, some instance which already exists and which will persist - like, perhaps, your view controller!
(Xcode 7)
Use this:
override func viewDidLoad() {
super.viewDidLoad()
// Setting the delegate
self.textField3.delegate = self
self.editingSwitch.setOn(false, animated: false)
}
// Text Field Delegate Methods
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return self.editingSwitch.on
}
#IBAction func toggleTheTextEditor(sender: AnyObject) {
if !(sender as! UISwitch).on {
self.textField3.resignFirstResponder()
}
}

hide keyboard for text field in swift programming language

I have little experience in Objective-C. I want to hide the keyboard for a text field using the Swift programming language.
I also tried this
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
But the method is not getting triggered when I hit return. Anyone have any luck with this?
I think the Problem is with setting the Delegate.
Please set textfield Delegate to your ViewController like this
class ViewController: UIViewController,UITextFieldDelegate {
and then create the IBOutlet for your text field like this
#IBOutlet var txtTest : UITextField = nil
make sure that it is connected to your text field on your view in storyboard.
finally set its Delegate using
txtTest.delegate=self
We are almost done. Now place this delegate function into your class.
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
return true;
}
Hope this will solve your issue.
Just override the UIViewController method called "touchesBegan" and set endEditing to true. Just like this:
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
self.view.endEditing(true)
}
In order to hide the keyboard when you pressed a button, you need to use the following function.
self.view.endEditing(true)
This works when a button is pressed.
Hope this helps someone out there.
Here we go:
Add a textField to your View
Create a new Swift file
Set this new file as a Class for that particular View
Add a TextField to your View
Create an Outlet for the textfield (my is named "txtField" !)
Substitute any code in the Swift Class file with this:
import Foundation
import UIKit
//01 create delegation
class MyViewController2: UIViewController,UITextFieldDelegate {
#IBOutlet weak var txtField: UITextField!=nil
override func viewDidLoad() {
super.viewDidLoad()
// additional setup after loading the view
//02 set delegate to textfield
txtField.delegate = self
}
//03 textfield func for the return key
func textFieldShouldReturn(textField: UITextField) -> Bool {
txtField.resignFirstResponder()
return true;
}
//textfield func for the touch on BG
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
txtField.resignFirstResponder()
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//dispose of any resources that can be recreated
}
}
Try it out, be happy & say thanks !
Now In Swift 3/4/5, the easiest methods are
Method 1: called when 'return' key pressed.
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField1.resignFirstResponder()
textField2.resignFirstResponder()
return true;
}
Method 2: called when 'return' key pressed.
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
self.view.endEditing(true)
return true;
}
Method 3: Global Method Write in view did load
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
Note: Don't forget to add this. Other wise its not work.
UIGestureRecognizerDelegate, UITextFieldDelegate
I hope it will work for you :)
In simple way to hide the keyboard just override the UIView "touchBegan method". So when you tap any where in the view keyboard is hide.
here is the sample code.. (Swift 3.0 Updated code)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
self.view.endEditing(true)
}
Like #spfursich said, The best way is, when user touch anywhere above the keyboard the keyboard will disappear. Here is the code :
override func viewDidLoad() {
super.viewDidLoad()
var tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
self.view.addGestureRecognizer(tap)
}
func DismissKeyboard(){
self.view.endEditing(true)
}
Add UITextFieldDelegate to the class declaration:
class ViewController: UIViewController, UITextFieldDelegate
Connect the textfield or write it programmatically
#IBOutlet weak var userText: UITextField!
set your view controller as the text fields delegate in view did load:
override func viewDidLoad() {
super.viewDidLoad()
self.userText.delegate = self
}
Add the following function
func textFieldShouldReturn(userText: UITextField!) -> Bool {
userText.resignFirstResponder()
return true;
}
with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.
UIApplication.sharedApplication().sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, forEvent:nil)
First you need to set delegate for your textfield then you need to include resignFirstResponder() to hide keyboard when press return button of keybaord.
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField .resignFirstResponder()
return true;
}
You can try this code to have the "return" key execute code.
func textFieldShouldReturn(textField: UITextField) -> Bool{
textField.resignFirstResponder()
performAction()
return true;
}
func performAction(){
//execute code for your action inside this function
}
Hope this can help you.
You can also do like this:
add event "Did end on exit" from connections inspector of your TextField
and connect it to method from relevant ViewController
In my example I connect it to method called 'ended'
declare sender as UITextField and then call sender.resignFirstResponder();
Like this:
#IBAction func ended (sender: UITextField){ sender.resignFirstResponder(); }
Here i have solved the problem, that when keypad opens and the view gets hidden behind the keypad.... that time we need to change the UI constraints dynamically in order to make the whole view visible. In my case i am changing the bottonConstraint of the UITextField dynamically.
So, here goes the complete code. I have one UITextView and UITextField on UIViewController to work on for just testing...
import UIKit
class ViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {
#IBOutlet weak var textView: UITextField!
#IBOutlet weak var textField: UITextView!
/*Height Constraint for textField*/
#IBOutlet weak var bottom: NSLayoutConstraint!
var defaultHeight:CGFloat = 0.0;
override func viewDidLoad() {
super.viewDidLoad()
defaultHeight = bottom.constant;
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}
override func resignFirstResponder() -> Bool {
textView.resignFirstResponder();
textField.resignFirstResponder();
return true;
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
resignFirstResponder()
print("touched began")
}
func textViewDidEndEditing(textView: UITextView) {
resignFirstResponder()
print("text view did end editing")
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
resignFirstResponder()
print("text view should end editing")
return true;
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
print("text field should return")
resignFirstResponder()
return true;
}
func textFieldDidEndEditing(textField: UITextField) {
resignFirstResponder()
print("did end editing")
}
func keyboardWillShow(notification: NSNotification) {
print("keyboard will show.............")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
let a = keyboardSize.height;
self.bottom.constant = a + defaultHeight;
self.view.updateConstraints();
}
}
func keyboardWillHide(nofication:NSNotification)
{
print("keyboard will hide................")
bottom.constant = defaultHeight;
self.view.updateConstraints();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
when you call your UIAlertController, place condition in the completion handler if you'd like to hide the keyboard.
self.present('nameOfYourUIAlertController', animated: true, completion: {
if condition == true {
'nameOfYourUIAlertController'.textFields![0].resignFirstResponder()
}
})
This works great for me.

How to hide keyboard in swift on pressing return key?

I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
the method resignfirstresponder is not getting in function.
You can make the app dismiss the keyboard using the following function
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
Here is a full example to better illustrate that:
//
// ViewController.swift
//
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var myTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
Code source: http://www.snip2code.com/Snippet/85930/swift-delegate-sample
The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:
// Called on 'Return' pressed. Return false to ignore.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
No Delegate Needed
You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:
#IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
Super simple.
(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)
Add UITextFieldDelegate to the class declaration:
class ViewController: UIViewController, UITextFieldDelegate
Connect the textfield or write it programmatically
#IBOutlet weak var userText: UITextField!
set your view controller as the text fields delegate in view did load:
override func viewDidLoad() {
super.viewDidLoad()
self.userText.delegate = self
}
Add the following function
func textFieldShouldReturn(userText: UITextField!) -> Bool {
userText.resignFirstResponder()
return true;
}
with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.
I hate to add the same function to every UIViewController.
By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".
extension UIViewController: UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)
Simple Swift 3 Solution:
Add this function to your view controllers that feature a text field:
#IBAction func textField(_ sender: AnyObject) {
self.view.endEditing(true);
}
Then open up your assistant editor and ensure both your Main.storyboard is on one side of your view and the desired view controller.swift file is on the other. Click on a text field and then select from the right hand side utilities panel 'Show the Connection Inspector' tab. Control drag from the 'Did End on Exit' to the above function in your swift file. Repeat for any other textfield in that scene and link to the same function.
#RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field's class:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
Substitute your outlet's name for textField.
Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:
#IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
Connect all your text fields for that view controller to that action on the Did End On Exit event of each field.
Here's the Swift 3.0 update to peacetype's comment:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
When the user taps the Done button on the text keyboard, a Did End On Exit event will be generated; at that time, we need to tell the text field to give up control so that the keyboard will go away. In order to do that, we need to add an action method to our controller class.
Select ViewController.swift add the following action method:
#IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}
Select Main.storyboard in the Project Navigator and bring up the connections inspector. Drag from the circle next to Did End On Exit to the yellow View Controller icon in the storyboard and let go. A small pop-up menu will appear containing the name of a single action, the one we just added. Click the textFieldDoneEditing action to select it and that's it.
Swift 3
Add this code below to your VC
//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
return false;
}
Works for me
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)}
then you use this function
func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
Swift
Using optional function from UITextFieldDelegate.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(false)
}
false means that field can be ask to resign. true – force resign.
Make sure that your textField delegate is set to the view controller from which you are writing your textfield related code in.
self.textField.delegate = self
you can put this anywhere but not in a UIButton
func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
return (false)
}
then you can put this code in a button(also for example):
self.view.endEditing(true)
this worked for me
In the view controller you are using:
//suppose you are using the textfield label as this
#IBOutlet weak var emailLabel: UITextField!
#IBOutlet weak var passwordLabel: UITextField!
//then your viewdidload should have the code like this
override func viewDidLoad() {
super.viewDidLoad()
self.emailLabel.delegate = self
self.passwordLabel.delegate = self
}
//then you should implement the func named textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// -- then, further if you want to close the keyboard when pressed somewhere else on the screen you can implement the following method too:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true);
}
you should connect the UITextfied with a delegate of view controller to make this function called
All in One Hide Keyboard and Move View on Keyboard Open: Swift 5
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc func taped(){
self.view.endEditing(true)
}
#objc func KeyboardWillShow(sender: NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
#objc func KeyboardWillHide(sender : NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

Resources