Swiftui dismiss keyboard

Swiftui dismiss keyboard DEFAULT

 

 

You’re now watching this thread and will receive emails when there’s activity. Click again to stop watching or visit your profile/homepage to manage your watched threads.

 

You’ve stopped watching this thread and will no longer receive emails when there’s activity. Click again to start watching.

Hi,

I have TextField and a list with buttons NavigationLink.

When i tap on NavigationLink i need to dismiss the keyboard, how?

Thanks in advance.

Answers

 

One way to do this is by adding this extension to `UIView`:

 

Works in Xcode 12 beta


 

This does work, however
It seems to have a side effect of making a segmented picker inside the nav view unresponsive. (Oddly, a Toggle control does still work.)
Bug or feature I'm not sure.

I've tried the onTapGesture at different levels and also tried onDisappear, none of which resolved the issue.

xcode /iOS

 

You can create an extension of View with the hideKeyboard like sprykly said.

Then in your view:

Used in SwiftUI1

Sours: https://developer.apple.com/forums/thread/

Usage

How to hide keyboard when using SwiftUI?

How to hide using for below cases?

Case 1

I have and I need to hide the when the user clicks the button.

Case 2

I have and I need to hide the when the user taps outside.

How I can do this using ?

Note:

I have not asked a question regarding . I want to do it by using .

Answer #1:

You can force the first responder to resign by sending an action to the shared application:

Now you can use this method to close the keyboard whenever you desire:

If you want to close the keyboard with a tap out, you can create a full screen white view with a tap action, that will trigger the :

Answered By: rraphael

Answer #2:

After a lot of attempts I found a solution that (currently) doesn't block any controls - adding gesture recognizer to .

  1. If you want to close keyboard only on Tap outside (without handling drags) - then it's enough to use just and just copy step 3:
  2. Create custom gesture recognizer class that works with any touches:

  3. In in the , add next code:

  4. Implement to allow simultaneous touches.

Now any keyboard on any view will be closed on touch or drag outside.

P.S. If you want to close only specific TextFields - then add and remove gesture recognizer to the window whenever called callback of TextField

Answered By: Mikhail

Answer #3:

SwiftUI 3 (iOS 15+)

(Done button above the keyboard)

Starting with iOS 15 we can now use to control which field should be focused (see this answer to see more examples).

We can also add s directly above the keyboard.

When combined together, we can add a button right above the keyboard. Here is a simple demo:

enter image description here

SwiftUI 2 (iOS 14+)

(Tap anywhere to hide the keyboard)

Here is an updated solution for SwiftUI 2 / iOS 14 (originally proposed here by Mikhail).

It doesn't use the nor the which are missing if you use the SwiftUI lifecycle:


If you want to detect other gestures (not only tap gestures) you can use as in Mikhail's answer:


Here is an example how to detect simultaneous gestures except Long Press gestures:

Answered By: pawello

Answer #4:

I experienced this while using a TextField inside a NavigationView. This is my solution for that. It will dismiss the keyboard when you start scrolling.

Answered By: DubluDe

Answer #5:

@RyanTCB's answer is good; here are a couple of refinements that make it simpler to use and avoid a potential crash:

The 'bug fix' is simply that properly should be (yes, you might argue it can't happen.)

More interesting is how you can use it. For example, suppose you have a form with multiple editable fields in it. Just wrap it like this:

Now, tapping on any control that itself doesn't present a keyboard will do the appropriate dismiss.

(Tested with beta 7)

Answered By: Feldur

Answer #6:

I found another way to dismiss the keyboard that doesn't require accessing the property; as a matter of fact the compiler gives back a warning using

'keyWindow' was deprecated in iOS Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes

Instead I used this code:

Answered By: Lorenzo Santini

Answer #7:

SwiftUI in 'SceneDelegate.swift' file just add: .onTapGesture { window.endEditing(true)}

this is enough for each View using keyboard in your app

Answered By: Dim Novo

Answer #8:

My solution how to hide software keyboard when users tap outside. You need to use with to detect the entire View container. required to avoid blocking focus on . You can use instead of but NavigationBar items won't work.

Answered By: Victor Kushnerov

Answer #9:

add this modifier to the view you want to detect user taps

Answered By: RyanTCB

Answer #

I prefer using the , which does not cause the keyboard to blink when another is activated (side effect of ). The hide keyboard code can be a reusable function.

Answered By: George Valkov

Answer #

Because is deprecated.

Answered By: msk

Answer #

Pure SwiftUI (iOS 15)

SwiftUI in iOS 15 (Xcode 13) gained native support for programmatic focus of using new property wrapper.

To dismiss the keyboard, simply set view's to . The return key will dismiss keyboard automatically (since iOS 14).

Docs: https://developer.apple.com/documentation/swiftui/focusstate/

Pure SwiftUI (iOS 14 and below)

You can completely avoid interaction with UIKit and implement it in pure SwiftUI. Just add an modifier to your and change its value whenever you want to dismiss keyboard (on swipe, view tap, button action, ..).

Sample implementation:

Note that I only tested it in latest Xcode 12 beta, but it should work with older versions (even Xcode 11) without any issue.

Answered By: josefdolezal

Answer #

Seems like the solution is the only one like @rraphael pointed out.
The cleanest example I've seen so far is this:

and then using it in the

Answered By: zero3nna

Answer #

Expanding on the answer by @Feldur (which was based on @RyanTCB's), here is an even more expressive and powerful solution allowing you to dismiss keyboard on other gestures than , you can specify which you want in the function call.

Or using (just sugar for ?)

Please do note that if you use all gestures they might conflict and I did not come up with any neat solution solving that.

Answered By: Sajjon

Answer #

In addition to all answers about tapping outside of the textField, you may want to dismiss the keyboard when the user taps the return key on the keyboard:

define this global function:

And add use in argument it:

Benefits

  • You can call it from anywhere
  • It's not dependent on UIKit or SwiftUI (can be used in mac apps)
  • It works even in iOS 13

Demo

demo

Answered By: Mojtaba Hosseini

Answer #

This method allows you to hide the keyboard on spacers!

First add this function (Credit Given To: Casper Zandbergen, from SwiftUI can't tap in Spacer of HStack)

Next add the following 2 functions (Credit Given To: rraphael, from this question)

The function below would be added to your View class, just refer to the top answer here from rraphael for more details.

Finally, you can now simply call

This will make any spacer area close the keyboard now. No need for a big white background view anymore!

You could hypothetically apply this technique of to any controls you need to support TapGestures that do not currently do so and call the function in combination with to close the keyboard in any situation you desire.

Answered By: Joseph Astrahan

Answer #

Based on @Sajjon's answer, here is a solution allowing you to dismiss keyboard on tap, long press, drag, magnification and rotation gestures according to your choice.

This solution is working in XCode

Answered By: Nicolas Mandica

Answer #

Expanding the answer by josefdolezal above, you can hide keyboard when user taps anywhere outside the textfield like below:

Answered By: Hasaan Ali

Answer #

So far above options did not work for me, because I have Form and inside buttons, links, picker

I create below code that is working, with help from above examples.

Usage:

Answered By: zdravko zdravkin

Answer #

Something I found that works very nice is

Then add to the view struct:

Then

Answered By: Sergio Bost

Answer #

Simple solution for clicking "outside" that worked for me:

First provide a ZStack before all views. In it, put a background (with the color of your choosing) and supply a tap Gesture. In the gesture call, invoke the 'sendAction' we've seen above:

sample

Answered By: Ethan Halprin

Answer #

A cleaner SwiftUI-native way to dismiss the keyboard via tap without blocking any complicated forms or whatnot credit to @user for flagging GestureMask as a clean approach.

  1. Monitor UIWindow.keyboardWillShowNotification / willHide

  2. Pass the current keyboard state via an EnvironmentKey set at the/a root view

Tested for iOS

Attach dismiss gesture to the form

Setup monitor in root view

SwiftUI Gesture + Sugar

EnvironmentKey

Answered By: Ryan

Answer #

True SwiftUI Solution

this will work flawlessly

Answered By: Dan Fu

Answer #

SwiftUI released on June/ with Xcode 12 and iOS 14 adds hideKeyboardOnTap() modifier. This should solve your case number 2. The solution for your case number 1 comes for free with Xcode 12 and iOS the default keyboard for TextField hides automatically when the Return button is pressed.

Answered By: Marcel Mendes Filho

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa , cc by-sa and cc by-sa .


Sours: https://www.py4u.net/discuss/
  1. Hudson river inlay hummingbird
  2. Brain games numbers
  3. Customized graduation bear

Dismissing The Keyboard In SwiftUI

Jonathan Badger

SwiftUI, Apple’s declarative framework for rapid user interface development, has continued to mature as a useful alternative to UIKit with a release at WWDC this year. As a newbie to the framework, I enjoy the instant feedback that the canvas preview provides with each code modification and am thoroughly impressed by the elegance and simplicity of SwiftUI’s design. That being said, I have run into odd behaviors and challenging problems that make me want to tear my hair out at times. One such issue, which at first seems trivial, is how to dismiss the keyboard when a user taps an area on the screen that is outside the bounds of a TextField or TextEditor view. Here, I will discuss a few of the common issues surrounding keyboard dismissal and provide two solutions and workarounds that I have found after an embarrassing amount of googling and combing of StackOverflow.

Notes: 1. A demo iOS app that accompanies this post is available on GitHub. 2. This article was written using XCode , SwiftUI , and compiled for iOS

The crux of the problem

SwiftUI doesn’t currently expose a mechanism for manual keyboard dismissal from within its own framework, so we have to fall back on UIKit. In UIKit, views that utilize the keyboard such as and can be dismissed by calling resignFirstResponder on the view itself, or endEditing on one of its parent views. Code in a simple view controller might look like this:

Here I have implemented both options for keyboard dismissal on a UITextField named . To add support for keyboard dismissal on taps outside of we add a tap gesture to the view controller’s view in . When an outside tap is recognized gets called and the view controller’s view calls endEditing. This in turn leads to textField calling resignFirstResponder, dismissing the keyboard. As a second option, we also have a button that when pressed calls dismissKeyboardFrom(view:). Here we pass in and directly call resignFirstResponder to dismiss the keyboard.

Side note:Both of these methods utilize the responder chain. If you are unfamiliar with the responder chain or need a refresher on UIResponder, UIEvent, UIControl, and how touch events and other gestures are handled in UIKit I would highly recommend reading this excellent article written by Bruno Rocha from Better Programming on Medium. The official docs on the responder chain from Apple are also extremely helpful and well written.

Solutions

So how do we bring this behavior into SwiftUI?

Option 1

The first solution I found comes from HackingWithSwift. Here, they suggest extending the protocol and utilizing the responder chain to send out a message. The extension looks like this:

This solution works beautifully if you attach the function to a submit button as they do in their example:

One would have hoped we could extend this idea by adding a tap gesture view modifier to a or to get the keyboard to dismiss on an outside tap as in:

Adding onTapGesture to a VStack (pink) still leaves a lot of non-interactive white space.

But this won’t work as expected. The first problem is that views created in SwiftUI typically only cover a portion of the screen, unlike the view associated with a view controller, which usually covers the entire screen. In the example on the right I have colored the background of the pink and as you can see, adding to the VStack will still leave a lot of non-interactive whitespace, which may be frustrating to users as they have to find just the right spot to get the behavior they expect.

The second problem is that when you try and use in a it may break some of the other interactive controls in the view. For example, if we have something like:

fix1_screenshot.jpg

Our keyboard will show and dismiss, but we can no longer interact with the picker view or press the submit button. Clearly, we need to try something else.







Option 2

The second fix I am going to show you adds keyboard dismissal App-wide and fixes the issues we observed in the last section. The original solution and other ideas from StackOverflow can be found here. In short, you can add a tap gesture recognizer to the underlying of the app that acts in a similar fashion to how we set up keyboard dismissal in UIKit by adding a tap gesture to the view of our view controller. To begin, extend UIApplication with a new method:

The method creates a , , that will target the App’s window and call to dismiss the keyboard. Since we still want the other parts of the user experience to function as normal, we set to . We set the as the delegate for (you’ll see why in a minute) and add the gesture to the first window in the windows array of .

Simultaneous gestures, such as a double tap, are important for selecting text in a . If we leave things as they stand, by default our new tap gesture will get called for both double and single taps, meaning when we try and double tap to select text, it will dismiss the keyboard. Oops! To fix this we can implement the gestureRecognizer(_ gestureRecognizer: , shouldRecognizeSimultaneouslyWith otherGestureRecognizer: ) delegate method of and return false.

The last step is to add the gesture to the app window when the application launches, which can be done like this if you are using the new SwiftUI App lifecycle:

Or, if you are still using the UIKit lifecycle you can instead skip extending UIApplication and set up your SceneDelegate similar to:

fix2_final.gif

The final results give us the user interaction we were looking for. Touching anywhere outside of the TextField dismisses the keyboard and all of our other controls work as expected. Success!

Final Thoughts

The second solution appears to give us back the behavior we are interested in, but I do have a few concerns that should be mentioned. First, I haven’t played much with apps that support multiple windows for iPads, but I suspect this current fix may not work as expected in a multi-window scenario. Second, I am a bit concerned future updates to SwiftUI and its inner workings may break this current fix, or worse, introduce new bugs that are hard to diagnose. My hope is that in the next update to SwiftUI Apple will give us an official solution to manual keyboard dismissal. At least we have a solution that can keep us productive while we wait.

Sours: https://www.dabblingbadger.com/blog//11/5/dismissing-the-keyboard-in-swiftui
SwiftUI - How to close/dismiss keyboard

How to dismiss the keyboard for a TextField

Paul Hudson    @twostraws   

Updated for Xcode

Updated in iOS 15

SwiftUI’s will show the keyboard automatically when activated, but before iOS 15 it was tricky to hide the keyboard when you’re done – particularly if you’re using the modifier with something like , , or .

If you’re supporting only iOS 15 and later, you can activate and dismiss the keyboard for a text field by focusing and unfocusing it. In its simplest form, this is done using the property wrapper and the modifier – the first stores a Boolean that tracks whether the second is currently focused.

So, we could write a simple view that hides the keyboard when a button is tapped:

Download this as an Xcode project

For more advanced uses, you can use to track an optional enum case that determines which form field is currently focused. For example, we might show three text fields asking the user for various pieces of information, then submit the form once the final piece has arrived:

Download this as an Xcode project

Important: You should not attempt to use the same focus binding for two different form fields.

If you have to support iOS 14 and 13, things are trickier. In fact, I want to make one thing clear: there is no built-in way of doing this with SwiftUI in iOS 13 and 14 – there’s no simple modifier we can attach, so if you were struggling to solve this it’s not because you weren’t trying hard enough.

To force SwiftUI to hide your keyboard, you need to use this code:

Yes, that’s very long, but it asks UIKit to search through what’s called the responder chain – the collection of controls that are currently responding to user input – and find one that is capable of resigning its first responder status. That’s a fancy way of saying “ask whatever has control to stop using the keyboard”, which in our case means the keyboard will be dismissed when a text field is active.

Because that code isn’t particularly easy to read, you should consider wrapping it in an extension such as this:

You can now write from inside any SwiftUI view.

How you use that depends on your code, but here’s a simple example that shows a decimal pad text field with a button to dismiss it:

Important: If you’re using Xcode 12 you need to use rather than .

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Sours: https://www.hackingwithswift.com/quick-start/swiftui/how-to-dismiss-the-keyboard-for-a-textfield

Keyboard swiftui dismiss

How to hide keyboard when using SwiftUI?

SwiftUI 3 (iOS 15+)

(Done button above the keyboard)

Starting with iOS 15 we can now use to control which field should be focused (see this answer to see more examples).

We can also add s directly above the keyboard.

When combined together, we can add a button right above the keyboard. Here is a simple demo:

enter image description here

SwiftUI 2 (iOS 14+)

(Tap anywhere to hide the keyboard)

Here is an updated solution for SwiftUI 2 / iOS 14 (originally proposed here by Mikhail).

It doesn't use the nor the which are missing if you use the SwiftUI lifecycle:


If you want to detect other gestures (not only tap gestures) you can use as in Mikhail's answer:


Here is an example how to detect simultaneous gestures except Long Press gestures:

Sours: https://stackoverflow.com/questions//how-to-hide-keyboard-when-using-swiftui
SwiftUI - Intro to MVVM - Example Refactor - Model View ViewModel

.

Similar news:

.



543 544 545 546 547