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 Answer 1

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()
         }
       }
    
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.