0

I have a very basic onboarding for my app where there are few screens in a tabview with the pagetabviewstyle, and I am having trouble getting the keyboard avoidance behavior to work.

If I have have the tabview set with .ignoresSafeArea, then the keyboard doesn't avoid my textfields.

[Tab View With IgnoresSafeArea][1]
[Page With TextField][2]
[Before TextField Pressed][3]
[Keyboard Covers TextField][4]

If I remove the .ignoresSafeArea then the keyboard pushes the pagetabview dot indicators up the screen into the middle of the textfield.

[Keyboard Avoids With Page Dots Pushed Into TextField][5]

My ideal outcome would be to have the entire TabView IgnoreSafeArea without disabling the keyboard avoidance. I've checked online for a while without seeing any information on this issue. Thanks in advance for the help and suggestions!

[1]: https://i.stack.imgur.com/flKCY.png
[2]: https://i.stack.imgur.com/lNSBR.png
[3]: https://i.stack.imgur.com/DWZzN.jpg
[4]: https://i.stack.imgur.com/9ktwz.jpg
[5]: https://i.stack.imgur.com/Wwbwz.png

1 Answers1

0

I had the same issue and solved it by changing the tabViewStyle whenever the keyboard state changes. Publisher code from How to detect if keyboard is present in swiftui :


    var keyboardPublisher: AnyPublisher<Bool, Never> =
        Publishers.Merge(
            NotificationCenter.default
                .publisher(for: UIResponder.keyboardWillShowNotification)
                .map { _ in true },
            
            NotificationCenter.default
                .publisher(for: UIResponder.keyboardWillHideNotification)
                .map { _ in false }
        )
        .eraseToAnyPublisher() 

Create a state var in your view:

@State var keyboardShown: Bool

Hook up the publisher:

TabView {

}
    .onReceive(vm.keyboardPublisher) { // <-- wherever you put your publisher
        self.keyboardShown = $0
    }

And modify the tab view style accordingly:

TabView {

}
    .tabViewStyle(.page(indexDisplayMode: keyboardShown ? .never : .automatic))

It works surprisingly well.

atultw
  • 921
  • 7
  • 15