0

I am currently making an app that takes in three user inputs for a red, green, and blue color value between 0 and 255 through separate TextField views. Right now, the user can input the values fine but there is no way of tabbing out of the keyboards. I understand there are two main ways to go about this. The first is adding a return button to the keyboard and the second is exiting out through a tap gesture.

I am fairly new to SwiftUI and I keep seeing online that the best solution is to override the viewDidLoad function and set a tap gesture in there. I am honestly not sure what the viewDidLoad function is and I am still very confused after researching it. At the moment, I am also not very familiar with UIViewControllers.

Is there an easier way to solve my issue or will I have to use a UIViewController and override the viewDidLoad function? enter code here

VStack {
    TextField("255", text: $redC) { editing in
        isEditing = editing
        redV = (redC as NSString).doubleValue
    } onCommit: {
        redV = (redC as NSString).doubleValue
    }
    TextField("255", text: $greenC) { editing in
        isEditing = editing
        greenV = (greenC as NSString).doubleValue
    } onCommit: {
        greenV = (greenC as NSString).doubleValue
    }
    TextField("255", text: $blueC) { editing in
        isEditing = editing
        blueV = (blueC as NSString).doubleValue
    } onCommit: {
        blueV = (blueC as NSString).doubleValue
    }
}
.multilineTextAlignment(.center)
.keyboardType(.numberPad)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
KevinKrupa
  • 11
  • 2
  • My work is being done all in SwiftUI – KevinKrupa Oct 14 '21 at 15:55
  • Does this answer your question? [How to hide keyboard when using SwiftUI?](https://stackoverflow.com/questions/56491386/how-to-hide-keyboard-when-using-swiftui) – jnpdx Oct 14 '21 at 15:57
  • It is definitely what I need but I am still getting an issue with sendAction where it is not in my scope – KevinKrupa Oct 14 '21 at 16:12
  • this could be useful: https://www.hackingwithswift.com/quick-start/swiftui/how-to-dismiss-the-keyboard-for-a-textfield – Abv Oct 14 '21 at 16:13
  • sendAction is not used in all of the answers in the link I posted. Please read further — there are many answers with different solutions and many upvotes – jnpdx Oct 14 '21 at 16:14

1 Answers1

0

Use onTapGesture closure

First Create an extension in UIApplication like that,

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


Add this in VStack like that,

 VStack {

      // contents

       }
        .onTapGesture {
               UIApplication.shared.resignFirstResponder()
        }


Shahriar Nasim Nafi
  • 1,160
  • 15
  • 19