Swift how to hide keyboard

Swift how to hide keyboard

Тап жест для скрытия клавиатуры в iOS (Swift 3)

В данной статье разберем, как скрывать клавиатуру по нажатию на вьюху от самых основ до реализации в одну строчку или совсем без кода.

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Основы

Достаточно часто встречается следующий кейс: по нажатию на задний фон скрывать клавиатуру.

В данной статье используется Swift 3, но можно реализовать и на других версиях и на Objective-C

Проблемы данного кода:

Делаем читабельным

Для решения первой проблемы мы можем вынести код создания и добавления жеста в отдельную функцию:

Кода стало еще больше, но он стал чище, логичней и приятней глазу.

Уменьшение кода

Для решения второй проблемы у UIView есть метод:

Он как раз отвечает за снятие выделения с самой вьюхи или ее subview. Благодаря ему мы можем сильно упростить наш код:

Код стал радовать глаз! Но копировать это в каждый контроллер все еще придется.

Решение копирования

Для переиспользуемости вынесем наш метод добавления в extension контроллера:

И код нашего контроллера будет выглядеть следующим образом:

Чисто, одна строчка кода, и она переиспользуема! Идеально!

Несколько вьюх

Решение выше — очень хорошее, но в нем кроется один минус: мы не можем добавить жест на конкретную вьюху.

Для решения данного кейса воспользуемся расширением UIView :

и соответственно код контроллера будет выглядеть так:

Тут возникает другая проблема: данное расширение решает проблему только для вьюхи контроллера. Если мы добавить someView на view и на нее повесим жест, то не сработает. Это все из-за того, что метод endEditing работает только для вьюхи, которая содержит активную вьюху или сама таковой является, а нашего текстового поля скорее всего не будет в нем. Решим данную проблему.

Получаем view контроллера через расширение UIView:

Скажу сразу, изменив селектор на:

работать все еще не будет. Нам необходимо добавить метод, который будет вызывать конструкцию выше:

Вот теперь заменяем селектор на:

Итак, расширение для UIView будет выглядеть следующим образом:

Теперь, используя addTapGestureToHideKeyboard() для любой вьюхи мы будем скрывать клавиатуру.

KeyboardHideManager

Решением выше я пользовался долгое время, но потом стал замечать, что даже одна строка загрязняет функцию установки вьюх. Так же, (редко, но все же бывает) не очень красиво выглядит, когда это единственный метод во viewDidLoad :

Вместе с пробелом это занимает 5 строк, что сильно сказывается на чистоте контроллера! У меня появилась идея сделать все это без кода, чтобы не было в контроллере и одной лишней строчки. Я создал класс, который можно добавить в IB с помощью Object

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

И с помощью @IBOutlet привязать нужные нам вьюхи:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Реализация данного класса наипростейшая — добавляем жест на каждую вьюху с помощью выше созданных функций:

Чтобы воспользоваться данным классом, нужно три простых действия:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Да, больше действий, чем написать одну строку (или несколько строк, если несколько определенных вьюх), за то этой самой строки нету в контроллере.

Кто-то может сказать, что лучше написать строку в коде, так понятнее, и будут правы, с одной стороны. Я за то, чтобы вынести из контроллера, все что можно и тем самым его облегчить.

Данный класс можете подключить через CocoaPods или просто скопировать в проект.

Ссылка на исходный код KeyboardHideManager с полным ReadMe о самой библиотеке и ее подключении.

Разобрали реализацию популярного кейса, рассмотрели несколько его решений, в одну строку и без кода вообще. Используйте тот способ, который больше нравится.

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:

the method resignfirstresponder is not getting in function.

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

20 Answers 20

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You can make the app dismiss the keyboard using the following function

Here is a full example to better illustrate that:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

You can create an action outlet from the UITextField for the «Primary Action Triggered» and resign first responder on the sender parameter passed in:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

(Thanks to Scott Smith’s 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)

Add UITextFieldDelegate to the class declaration:

Connect the textfield or write it programmatically

set your view controller as the text fields delegate in view did load:

Add the following function

with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

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».

When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.

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:

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.

for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()

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:

To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field’s class:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:

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:

How to hide keyboard in Swift app during UI testing

I just started with UI testing in Xcode 7 and hit this problem:

I need to enter text into a textfield and then click a button. Unfortunately this button is hidden behind the keyboard which appeared while entering text into the textfield. Xcode is trying to scroll to make it visible but my view isn’t scrollable so it fails.

My current solution is this:

I can do this because my ViewController is intercepting touches:

I am not really happy about my solution, is there any other way how to hide the keyboard during UI testing?

10 Answers 10

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If you have set up your text fields to resign FirstResponder (either via textField.resignFirstResponder() or self.view.endEditing(true) ) in the textFieldShouldReturn() delegate method, then

Swift 5 helper function

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Based on a question to Joe’s blog, I have an issue in which after a few runs on simulator the keyboards fails to hide using this piece of code:

So, I changed it to: (thanks Joe)

What I try to do here is detecting if the keyboard stills open after tap the hide button, if it is up, I type a «\n», which in my case closes the keyboard too.

This also happens to be tricky, because sometimes the simulator lost the focus of the keyboard typing and this might make the test fail, but in my experience the failure rate is lower than the other approaches I’ve taken.

How to hide the keyboard when I press return key in a UITextField?

Clicking in a textfield makes the keyboard appear. How do I hide it when the user presses the return key?

12 Answers 12

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

First make your file delegate for UITextField

Then add this method to your code.

Also add self.textField.delegate = self;

In viewDidLoad declare:

Then, include the override of the delegate method:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Try this in Swift,

Step 1: Set delegate as self to your textField

Step 2: Add this UITextFieldDelegate below your class declaration,

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

In swift do like this:
First in your ViewController implement this UITextFieldDelegate For eg.

Now add a delegate to a TextField in which you want to dismiss the keyboard when return is tapped either in viewDidLoad method like below or where you are initializing it. For eg.

Now add this method.

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Swift 4

that’s it. Before writing a code dont forget to set delegate of a UITextField and set Return key type to «Done» from properties window.(command + shift + I).

Then, in textField delegate method

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.

Then all you need to do in the storyboard is set the fields to use the class:

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

You can connect «Primary Action Triggered» (right click on UITextField) with an IBAction and you can resign first responder (without delegation). Example (Swift 4):

Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.

Either create an extension or use the ViewController in which you’d like to use this but make sure to implement UITextFieldDelegate. For reusability’s sake I found it easier to use an extension:

but the alternative works as well:

Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)

In your viewDidLoad method, set the textfield’s delegate to self

That should be all. Now, when you press return the textFieldShouldReturn should be called.

Hide keyboard automatically in swift

Is there a way to automatically hide keyboard in swift after inputting four characters? I actually have a code that hides the keyboard but the user has to click anywhere on the screen. Here’s the code:

Thanks in advance!

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If I got your question correctly, Consider below example code:

With above code keyboard will hide when textField have 4 characters and after that if user again tap on textField keyboard will pop up be user will not able to enter any text into textField and keyboard will hide again.

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Hope this will help.

Swift how to hide keyboard. Смотреть фото Swift how to hide keyboard. Смотреть картинку Swift how to hide keyboard. Картинка про Swift how to hide keyboard. Фото Swift how to hide keyboard

Here is the simplest way to hide the keyboard or a numberpad. First you need a button and you need to make it the size of the screen.Send it to the back of the scene and connect it to an IBAction.Then you code should look like this:

This should work for all types of keyboard.

This worked for me:

I also recommend you setting the

so the textField gets cleared when the user clicks on it again.

You should use textfield delegate shouldChangeCharactersInRange something like,

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *