How To Hide Keyboard In iOS Applications ?

How To Hide Keyboard In iOS

Hi, In this post, I'll show you how to hide keyboard in your iOS apps. So, lets get started and see how to do it.

You can also watch this tutorial on my YouTube channel here: How To Hide Keyboard in iOS using Swift ?

First of all, open your Xcode and create a new Single View Application.



Now, give some name to your product like "HideYourKeyboard", and make sure to choose Swift as the language.



Now, Go to Main.storyboard and drag a text field on it. Add some constraints on this text field as shown in the image below:



Now, open the Assistant Editor and make sure both storyboard and view controller files are visible as shown in the picture below:



Now, ctrl-drag your text field to viewcontroller.swift file and create its outlet.

Once done, then close this section and open your viewcontroller.swift file.

Here, first of all add UITextFieldDelegate method as shown in the image below.


Now, we'll add 2 functions for hiding the keyboard.

1. By using touchesBegan method which will enable users to hide the keyboard by clicking anywhere on the app screen.

2. By using textFieldShouldReturn method which will enable users to hide the keyboard by pressing the return key on the keyboard.
Note: Make sure to add nameTF.delegate = self in your viewDidLoad method. (nameTF is the name of textfield in our case)

So, now add both these functions in your code and your whole code will look like this:
_________________________________________________________________________________

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet var nameTF: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        nameTF.delegate = self    
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        nameTF.resignFirstResponder()
        return true
    }

}
_________________________________________________________________________________
So, that's all for this tutorial. By using these 2 very simple functions, you can hide your keyboard in your iOS applications.

I hope this post may help someone, somehow!

If you've any doubts or need any further help, then do message me in comments section below and I'll try to respond you as soon as possible.

Thanks for your time. Keep coding...



Comments

Popular posts from this blog

How To Make The Device Vibrate Or Ring- An iOS Swift Tutorial

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

How To Parse JSON Data In iOS (Swift 3 + Xcode 8) ?