Dismiss keyboard in iOS - ios

I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
and also setting a text field input as first responder:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
pressureInput.resignFirstResponder()
}
I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.

first of all write this extension in any swift file
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
Than in viewDidLoad of that View only call in any view controller there are textFields.
self.hideKeyboardWhenTappedAround()

Swift 4, 5. I always use hide keyboard when tapped around and return button.
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
emailTextField.delegate = self // your UITextfield
passwordTextField.delegate = self // your UITextfield
}
// Hide Keyboard
extension EmailAutorization: UITextFieldDelegate {
// Return button tapped
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Around tapped
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EmailAutorization.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}

Here is Solution of Dismiss Keyboard and Move View Up 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)
}
//This Method Will Hide The Keyboard
#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
}
}
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)
}

Did you tried to debug the program to see if the code stops in the function at all(with break point)? Usually this code should work...Check if those textFields are in the super view or in a child view and if they are maybe you should call self.childView.endEditing(true).
If you really work with multiple textFields maybe you should try IQKeyboardManager library. I use it in all my projects. You can find it here: https://github.com/hackiftekhar/IQKeyboardManager. Simple to use and with good support. Just install it trough cocoa pods, put IQKeyboardManager.sharedManager().enable = true in the AppDelegate and you're ready to go. :)

Are you sure that touchesBegan is being called? If you're sure, try adding self.resignFirstResponder() to your touchesBegan function. This tells your view controller that it's no longer the first responder and should dismiss the keyboard.
If not, what you'll want to do is create a UITapGestureRecognizer, add it to your view, and wire it to a function that calls self.resignFirstResponder().

Related

Dismiss Keyboard And Allow Button Gesture Recognizers Swift iOS

I'm using this code to hide the keyboard when the user taps anywhere on the screen outside of the TextView:
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
tap.delegate = self
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
#objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view is UIButton {
return false
}
return true
}
The problem is I have a UIButton in this view as well - when I tap on the button, the button's gesture recognizer function is not called. Instead, dismissKeyboard is called. I already tried the suggestion of using tap.cancelsTouchesInView = false as well as the shouldReceive method, but neither of them work - in the shouldReceive method, when I tap on the button, the class of touch.view is UIView.
Does anybody know how to allow the user to hide the keyboard when clicking anywhere on screen, but also allow button action handlers to execute?
I fixed this using the following code:
I detect the location of the user's touch
I check if the touch is in the frame of each of the two buttons in my UIView
If this is true, I manually call the button handler and return false from the method
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if let view = self.view as? MyViewControllersView {
let location = touch.location(in: self.view)
if view.saveButton.frame.contains(location) {
view.saveHit()
return false
} else if view.scanButton.frame.contains(location) {
view.scanHit()
return false
}
}
return true
}
it works for me, please check out
//MARK:- View Lyfe cycle
override func viewDidLoad() {
super.viewDidLoad()
IQKeyboardManager.shared().isEnableAutoToolbar = false
// IQKeyboardManager.shared().disabledToolbarClasses = self
IQKeyboardManager.shared().isEnabled = false
self.keyboardWillShowAndHide()
initializeHideKeyboard()
}
//MARK:- KayBoard Handling...
//MARK:- Init Hide KeyBoard...
func initializeHideKeyboard(){
//Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(dismissMyKeyboard))
//Add this tap gesture recognizer to the parent view
view.addGestureRecognizer(tap)
}
//MARK:- Dismissing Keyboard...
#objc func dismissMyKeyboard(){
//endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
//In short- Dismiss the active keyboard.
view.endEditing(true)
}
//MARK:- Kayboard Hide and Show...
func keyboardWillShowAndHide(){
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboarddidHide),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
//MARK:- KeyBoard Will Show
#objc func keyboardWillShow(_ notification: Notification) {
self.arrConversationList.count
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.ChatBottomConstraint.constant = keyboardHeight - self.bottomLayoutGuide.length
DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
if self.arrConversationList.count > 0 {
let indexPath = NSIndexPath(row: self.arrConversationList.count-1, section: 0)
self.ConversationTblref.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: true)
}
})
self.tableviewbottomconstraintref.constant = 0
ConversationTblref.reloadData()
}
}
//MARK:- KeyBoard Will Hide
#objc func keyboarddidHide(_ notification: Notification) {
self.tableviewbottomconstraintref.constant = 0
self.ChatBottomConstraint.constant = 0
ConversationTblref.reloadData()
}
//MARK:- View Disappear for handleing kayboard...
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
IQKeyboardManager.shared().isEnableAutoToolbar = true
IQKeyboardManager.shared().isEnabled = true
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
}

Calling function when user taps anywhere on screen

In my app I have a small menu I made which is basically a UIView with two button on it. The menu opens when the user taps a button and closes also when the user taps the same button. I'd like the menu to close when the user taps anywhere outside of the menu UIView.
The menu:
You can also apply this easy way
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:)))
self.view.addGestureRecognizer(tapGesture)
func tapBlurButton(_ sender: UITapGestureRecognizer) {
if //checkmenuopen
{
closemenuhere
}
}
For that when you show the small menu, add below it a invisible button (UIColor.clear) with the entire screen as a frame. And it's action is to dismiss the menu of yours.
Make sure when you dismiss the small menu to dismiss thus button as well.
Hope this helps!
You can use basically touches began function
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("TAPPED SOMEWHERE ON VIEW")
}
There are several solutions to your case:
1- Implementing touchesBegan(_:with:) method in your ViewController:
Tells this object that one or more new touches occurred in a view or
window.
Simply, as follows:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// do something
}
2- Add a UITapGestureRecognizer to the main view of your ViewController:
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doSomething(_:)))
view.addGestureRecognizer(tapGesture)
}
func doSomething(_ sender: UITapGestureRecognizer) {
print("do something")
}
Or -of course- you could implement the selector without the parameter:
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doSomething))
view.addGestureRecognizer(tapGesture)
}
func doSomething() {
print("do something")
}
3- You could also follow Mohammad Bashir Sidani's answer.
I would suggest to make sure add the appropriate constraints to your button whether it has been added programmatically or by storyboard.
I'm not sure the code below will work in your case, just a advice.
class ViewController: UIViewController {
var closeMenuGesture: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
closeMenuGesture = UITapGestureRecognizer(target: self, action: #selector(closeMenu))
closeMenuGesture.delegate = self
// or closeMenuGesture.isEnable = false
}
#IBAction func openMenu() {
view.addGestureRecognizer(closeMenuGesture)
// or closeMenuGesture.isEnabled = true
}
#IBAction func closeMenu() {
view.removeGestureRecognizer(closeMenuGesture)
// or closeMenuGesture.isEnabled = false
}
}
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return touch.view === self.view // only valid outside menu UIView
}
}
And I never be in this situation so not sure making enable/disable closeMenuGesture is enough to ensure other controls work normally, or to add/remove closeMenuGesture is more insured.

How to setup the keyboard if l'am using two text fields

I've been trying to set up my keyboard since a few days ago, but I can't manage to do it. I just want the imageView to move up when I am writing in the bottom text field. In fact, it's working, but it also moves up when I try to write at the topTextField. I don't want that, because when that happens, I can't see the textField at the top, and I can't see what I'm writing.
I'll include my screenshots and my code.
In this image, I pressed the topTextField to write something, but as you can see, the topTextField is lost. I mean the view moves up when I press the topTextField and I don't want that. What I want is so that when I press the topTextField the keyboard should appear but the view should be at the same place.
And in the last one I pressed the textFieldBottom, and as you can see, it works. The view moves up so I can see what I'm writing inside the textFieldBottom.
Here is my code:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.subscribeToKeyboardNotifications()
self.subscribeToKeyboardNotificationsDown()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.unsubscribeToKeyBoardNotifications()
self.unsubscribeToKeyBoardNotificationsDown()
}
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)) , name: UIKeyboardWillShowNotification, object: nil)
}
func unsubscribeToKeyBoardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
view.frame.origin.y -= getKeyboardHeight(notification)
}
func subscribeToKeyboardNotificationsDown() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyBoardNotificationsDown() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillHide(notification: NSNotification) {
view.frame.origin.y += getKeyboardHeight(notification)
}
func getKeyboardHeight(notification:NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
// do one thing maintain one globle varible to save current textfield which is on editing mode based on that varible u put condition to move imageview
following example code will help you.
var currentTextField: UITextField
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
currentTextField = textField
return true
}
func keyboardWillShow(notification: NSNotification) {
if currentTextField == textFieldBottom {
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
When topTextField becomes first responder, you're changing view.frame.origin, this is moving your topTextField up. Instead of changing view frame, you can set constraints for bottomTextField and you can change constraints for bottomTextField programmatically in keyboardWillShow method. This way your view frame will not change and topTextField will not move up.

UITextField keyboard not dismissing

I have a UIViewController with a UITextField in it and I'm trying to dismiss the keyboard when I click away or the view is dismissed. However, when I call resignFirstResponder(), the keyboard still doesn't dismiss and I'm not quite sure why. Here's my code:
class MessageViewController: UIViewController, UITextFieldDelegate {
var messageTextField : UITextField = UITextField()
override func viewDidLoad() {
...
messageTextField.frame = CGRectMake(10, UIScreen.mainScreen().bounds.size.height-50, UIScreen.mainScreen().bounds.size.width-80, 40)
messageTextField.delegate = self
messageTextField.borderStyle = UITextBorderStyle.Line
messageTextField.becomeFirstResponder()
self.view.addSubview(messageTextField)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
...
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
println("Touched")
}
func keyboardWillShow(notification: NSNotification) {
var keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey]as? NSValue)?.CGRectValue()
let messageFrame = messageTextField.frame
let newY = messageFrame.origin.y - keyboardSize!.height
messageTextField.frame = CGRectMake(messageFrame.origin.x, newY, messageFrame.size.width, messageFrame.size.height)
}
func keyboardWillHide(notification: NSNotification) {
var keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey]as? NSValue)?.CGRectValue()
let messageFrame = messageTextField.frame
let newY = messageFrame.origin.y - keyboardSize!.height
messageTextField.frame = CGRectMake(messageFrame.origin.x, newY, messageFrame.size.width, messageFrame.size.height)
}
}
Does anyone know why the keyboard isn't dismissing? I added the UITextField to the view programmatically as opposed to using storyboard. Does that make a difference?
class ViewController: UIViewController,UITextFieldDelegate {
confirm protocols
messageTextField.delegate=self
set delegate
func textFieldShouldReturn(textField: UITextField!) -> Bool
{
messageTextField.resignFirstResponder()
return true;
}
Use this code..
The following is how I did for that problem. I hope this method solve your problem.
textfield
#IBOutlet var userID : UITextField!
function.
func textFieldShouldReturn(textField: UITextField!)-> Bool
{ userID.resignFirstResponder( )
return true
}
In your desired function, you need to write this syntax.
#IBAction func login(sender: AnyObject)
{
userID.resignFirstResponder( )
}
This is in ViewDidLoad or ViewDidAppear
override func viewDidLoad( )
{
userID.delegate = self;
}
I cannot comment on the previous user. That's why I write this one.
I hope this gives you idea.
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
//textField.resignFirstResponder()
return false
}
check delegate add into your viewDidLoad()
self.yourTextField.delegate = self;
how-to-dismiss-uitextfields-keyboard-in-your-swift-app
This might helps you :)
#vijeesh's answer will probably work, and the logic is almost correct, but it is technically wrong if you ever use more than one UITextField. textField is the UITextField parameter that is passed when textFieldShouldReturn is called. The problem is, you're just declaring:
textField.resignFirstResponder()
Your program doesn't know what UITextField you're referring to. Even though you may only have one textField in your program, and you know that it's your messageTextField, the program still doesn't know that. It just sees "textField". So you have have to tell it what to do for each UITextField in your program. Even if you have just one. This should work:
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == messageTextField {
messageTextField.resignFirstResponder()
}
return true
}
very simple.
first you add Tap Gesture
var tap = UITapGestureRecognizer(target: self, action: "handle:")
view.addGestureRecognizer(tap)
in function handle
func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
so you can dismiss keyboard when you click outside UITextField

Close iOS Keyboard by touching anywhere using Swift

I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C but I have no idea how to do that using Swift? Does anyone know?
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
#objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
Here is another way to do this task if you are going to use this functionality in multiple UIViewControllers:
// Put this piece of code anywhere you like
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
Now in every UIViewController, all you have to do is call this function:
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
}
This function is included as a standard function in my repo which contains a lot of useful Swift Extensions like this one, check it out: https://github.com/goktugyil/EZSwiftExtensions
An answer to your question on how to dismiss the keyboard in Xcode 6.1 using Swift below:
import UIKit
class ItemViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var textFieldItemName: UITextField!
#IBOutlet var textFieldQt: UITextField!
#IBOutlet var textFieldMoreInfo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textFieldItemName.delegate = self
textFieldQt.delegate = self
textFieldMoreInfo.delegate = self
}
...
/**
* Called when 'return' key pressed. return NO to ignore.
*/
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
(Source of this information).
Swift 4 working
Create extension as below & call hideKeyboardWhenTappedAround() in your Base view controller.
//
// UIViewController+Extension.swift
// Project Name
//
// Created by ABC on 2/3/18.
// Copyright © 2018 ABC. All rights reserved.
//
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tapGesture = UITapGestureRecognizer(target: self,
action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
#objc func hideKeyboard() {
view.endEditing(true)
}
}
Most important thing to call in your Base View Controller so that no need to call all time in all view controllers.
You can call
resignFirstResponder()
on any instance of a UIResponder, such as a UITextField. If you call it on the view that is currently causing the keyboard to be displayed then the keyboard will dismiss.
swift 5 just two lines is enough. Add into your viewDidLoad should work.
let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tapGesture)
If your tap gesture blocked some other touches, then add this line:
tapGesture.cancelsTouchesInView = false
for Swift 3 it is very simple
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
if you want to hide keyboard on pressing RETURN key
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
but in second case you will also need to pass delegate from all textFields to the ViewController in the Main.Storyboard
//Simple exercise to demonstrate, assuming the view controller has a //Textfield, Button and a Label. And that the label should display the //userinputs when button clicked. And if you want the keyboard to disappear //when clicken anywhere on the screen + upon clicking Return key in the //keyboard. Dont forget to add "UITextFieldDelegate" and
//"self.userInput.delegate = self" as below
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var userInput: UITextField!
#IBAction func transferBtn(sender: AnyObject) {
display.text = userInput.text
}
#IBOutlet weak var display: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//This is important for the textFieldShouldReturn function, conforming to textfieldDelegate and setting it to self
self.userInput.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//This is for the keyboard to GO AWAYY !! when user clicks anywhere on the view
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
//This is for the keyboard to GO AWAYY !! when user clicks "Return" key on the keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
Swift 3:
Easiest way to dismiss keyboard:
//Dismiss keyboard method
func keyboardDismiss() {
textField.resignFirstResponder()
}
//ADD Gesture Recignizer to Dismiss keyboard then view tapped
#IBAction func viewTapped(_ sender: AnyObject) {
keyboardDismiss()
}
//Dismiss keyboard using Return Key (Done) Button
//Do not forgot to add protocol UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
keyboardDismiss()
return true
}
In swift you can use
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
view.endEditing(true)
}
Just one line of code in viewDidLoad() method:
view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))
Dash's answer is correct and preferred. A more "scorched earth" approach is to call view.endEditing(true). This causes view and all its subviews to resignFirstResponder. If you don't have a reference to the view you'd like to dismiss, this is a hacky but effective solution.
Note that personally I think you should have a reference to the view you'd like to have resign first responder. .endEditing(force: Bool) is a barbaric approach; please don't use it.
I found the best solution included the accepted answer from #Esqarrouth, with some adjustments:
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboardView")
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboardView() {
view.endEditing(true)
}
}
The line tap.cancelsTouchesInView = false was critical: it ensures that the UITapGestureRecognizer does not prevent other elements on the view from receiving user interaction.
The method dismissKeyboard() was changed to the slightly less elegant dismissKeyboardView(). This is because in my project's fairly old codebase, there were numerous times where dismissKeyboard() was already used (I imagine this is not uncommon), causing compiler issues.
Then, as above, this behaviour can be enabled in individual View Controllers:
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
}
In storyboard:
select the TableView
from the the right-hand-side, select the attribute inspector
in the keyboard section - select the dismiss mode you want
Swift 3:
Extension with Selector as parameter to be able to do additional stuff in the dismiss function and cancelsTouchesInView to prevent distortion with touches on other elements of the view.
extension UIViewController {
func hideKeyboardOnTap(_ selector: Selector) {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
}
Usage:
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}
func dismissKeyboard() {
view.endEditing(true)
// do aditional stuff
}
I have use IQKeyBoardManagerSwift for keyboard. it is easy to use.
just Add pod 'IQKeyboardManagerSwift'
Import IQKeyboardManagerSwift and write code on didFinishLaunchingWithOptions in AppDelegate.
///add this line
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enable = true
To expand on Esqarrouth's answer, I always use the following to dismiss the keyboard, especially if the class from which I am dismissing the keyboard does not have a view property and/or is not a subclass of UIView.
UIApplication.shared.keyWindow?.endEditing(true)
And, for convenience, the following extension to the UIApplcation class:
extension UIApplication {
/// Dismisses the keyboard from the key window of the
/// shared application instance.
///
/// - Parameters:
/// - force: specify `true` to force first responder to resign.
open class func endEditing(_ force: Bool = false) {
shared.endEditing(force)
}
/// Dismisses the keyboard from the key window of this
/// application instance.
///
/// - Parameters:
/// - force: specify `true` to force first responder to resign.
open func endEditing(_ force: Bool = false) {
keyWindow?.endEditing(force)
}
}
Use IQKeyboardmanager that will help you solve easy.....
/////////////////////////////////////////
![ how to disable the keyboard..][1]
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
username.delegate = self
password.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
return true;
}
override func touchesBegan(_: Set<UITouch>, with: UIEvent?) {
username.resignFirstResponder()
password.resignFirstResponder()
self.view.endEditing(true)
}
}
If you use a scroll view, It could be much simpler.
Just select Dismiss interactively in storyboard.
Add this extension to your ViewController :
extension UIViewController {
// Ends editing view when touches to view
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.view.endEditing(true)
}
}
In Swift 4, add #objc:
In the viewDidLoad:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)
Function:
#objc func dismissKeyboard() {
view.endEditing(true)
}
import UIKit
class ItemViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var nameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.nameTextField.delegate = self
}
// Called when 'return' key pressed. return NO to ignore.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Called when the user click on the view (outside the UITextField).
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
As a novice programmer it can be confusing when people produce more skilled and unnecessary responses...You do not have to do any of the complicated stuff shown above!...
Here is the simplest option...In the case your keyboard appears in response to the textfield - Inside your touch screen function just add the resignFirstResponder function. As shown below - the keyboard will close because the First Responder is released (exiting the Responder chain)...
override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
MyTextField.resignFirstResponder()
}
This one liner resigns Keyboard from all(any) the UITextField in a UIView
self.view.endEditing(true)
Posting as a new answer since my edit of #King-Wizard's answer was rejected.
Make your class a delegate of the UITextField and override touchesBegan.
Swift 4
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
//Called when 'return' key is pressed. Return false to keep the keyboard visible.
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
// Called when the user clicks on the view (outside of UITextField).
override func touchesBegan(touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
For Swift3
Register an event recogniser in viewDidLoad
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))
then we need to add the gesture into the view in same viewDidLoad.
self.view.addGestureRecognizer(tap)
Then we need to initialise the registered method
func hideKeyBoard(sender: UITapGestureRecognizer? = nil){
view.endEditing(true)
}
Here is how to dismiss the keyboard by tapping anywhere else, in 2 lines using Swift 5.
(I hate to add another answer, but since this is the top result on Google I will to help rookies like me.)
In your ViewController.swift, find the viewDidLoad() function.
Add these 2 lines:
let tap: UIGestureRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tap)
You can also add a tap gesture recognizer to resign the keyboard. :D
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
backgroundView.addGestureRecognizer(recognizer)
}
func handleTap(recognizer: UITapGestureRecognizer) {
textField.resignFirstResponder()
textFieldtwo.resignFirstResponder()
textFieldthree.resignFirstResponder()
println("tappped")
}
Another possibility is to simply add a big button with no content that lies underneath all views you might need to touch.
Give it an action named:
#IBAction func dismissKeyboardButton(sender: AnyObject) {
view.endEditing(true)
}
The problem with a gesture recognizer was for me, that it also caught all touches I wanted to receive by the tableViewCells.
If you have other views that should receive the touch as well you have to set
cancelsTouchesInView = false
Like this:
let elsewhereTap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
elsewhereTap.cancelsTouchesInView = false
self.view.addGestureRecognizer(elsewhereTap)
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))
}
func tap(sender: UITapGestureRecognizer){
print("tapped")
view.endEditing(true)
}
Try this,It's Working

Resources