2

If the user clicks the button while editing the TextField (cursor flashing) in DataPtView, the app crashes.

In a list cell, I have the button, which impacts the view that is also shown in the cell. Here's a snippet, iPad specific.

CellView:

VStack{
  Button("TagOut"){
    self.tagOut.toggle()
  }
  
  if self.tagOut {
    TagOutView(question: question)
  }
  
  if !self.tagOut{
    if question.type == "Y/N"{
      YesOrNoView(question: question)
    } else if question.type == "DataPt"{
      DataPtView(question: question)
    } else {
      RecordEntryView()
  }
  ...

DataPtView:

...
TextField("Data: ", text: $collectedData)
       .onReceive(Just(collectedData)) {value in
         let filtered = value.filter {"01234567890-".contains($0)}
         if filtered != value{
           self.invalidCollectedData = true
         } else {
           self.invalidCollectedData = false
         }
 }
 ...

I'm also using an AdaptsToKeyboard ViewModifier for when CellView is covered by the keyboard. move-textfield-up-when-the-keyboard-has-appeared-in-swiftu

How do I prevent this from happening? If user hides the keyboard before clicking the button, everything is fine, but that isn't intuitive.

1 Answers1

1

What if you try to check if your modifier height is greater than 0 and based on this handle the button click. In your cell view define:

@State var keyboardHeight: CGFloat = 0

Change your AdaptsToKeyboardModifier to have binding var inside it:

struct AdaptsToKeyboard: ViewModifier {
    @Binding var currentHeight: CGFloat = 0
    ...
}

Now you need to initialize your modifier with the following constructor:

.modifier(AdaptsToKeyboard(currentHeight: $keyboardHeight))

Now you have two options to handle the button press:

  1. To disable the button interaction:

      Button("TagOut"){
        self.tagOut.toggle()
      }.disabled(keyboardHeight > 0)
    
  2. To ignore the press:

       Button("TagOut") {
         if self.keyboardHeight == 0 {
            self.tagOut.toggle()
         }
       }
    
Neil Galiaskarov
  • 5,015
  • 2
  • 27
  • 46
  • Thanks Neil! Worked great. I didn't like the idea of having a button that you can't push so I just hide it if keyboard > 0 – Daniel Price Jul 14 '20 at 19:49