SALE: Save 50% on all my books and bundles >>

SOLVED: TextField - Dismiss keyboard - Clear button

Forums > SwiftUI

hi everybody!

does anyone know an easy and elegant way of dismissing the keyboard when finished with entry (especially when using numberPad or decimalPad) from a textField in SwiftUI? Also to add an clearButton and once the entry is cleared, that the placeholder will be shown?

Thanks a lot in advance for helping me out! Rgds, Martin

   

Hi Martin Hope this helps. Not sure the best way but found it works for me

struct ContentView: View {
    @State private var someNumber = ""
    @State private var enteredNumber = ""

    var body: some View {
        VStack {
            Text("\(enteredNumber)")

            TextField("PlaceHolder", text: $someNumber)
                .keyboardType(.decimalPad)
            Button("Submit") {
                self.enteredNumber = self.someNumber
                self.someNumber = "" // Clear text
                UIApplication.shared.endEditing() // Call to dismiss keyboard
            }
        }
        .padding()
    }
}

// extension for keyboard to dismiss
extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

if you want the view to move up and down to make room for keyboard you will need to add a func with

NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { key in
            let value = key.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
            self.value = value.height
        }

        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { key in
            self.value = 0
        }

and add .onAppear(perform: ----) to the view

1      

Thanks a lot Nigel!

I had to chance my idea of creating my UI, but your way makes it really easy to use now. thanks a lot!

Rgds, Martin

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building in-app subscriptions are hard. RevenueCat makes it simple. With their open source SDKs, you can painlessly implement subscriptions for your app in hours, not months.

Explore the docs to learn more

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Cascable unleashes the power of your camera and unlocks powerful workflows for shooting, managing, and geotagging your photos.

 
Unknown user

Not logged in

Log in