OuSS
OuSS

Reputation: 69

SwiftUI in iOS14 Keyboard Avoidance for bottom View

In iOS14 SwiftUI introduced automatic keyboard avoidance. I have form in scrollView that take all screen expect bottom where I have a fixed button.

I want to ignore keyboard avoidance for that button but keep it for scrollView so the textfields move when the keyboard appears.

I tried this code but it didn't work:

struct ContentView: View {
    
    @State var text:String = ""
    
    var body: some View {
        
        VStack {
            ScrollView {
               TextField("Testing", text: $text)
            }
            Button("Validate", action: action)
              //.ignoresSafeArea(.keyboard) second try
        }
        //.ignoresSafeArea(.keyboard) first try
    }
}

First try: this applies globally, the bottom of the scrollView won't be accessible when keyboard is open.

Second try: this doesn't do anything (Button stays above the keyboard)

Upvotes: 2

Views: 942

Answers (1)

jpowell
jpowell

Reputation: 41

I actually just ran into this issue myself. I think there is a bug in SwiftUI that is causing the button to keep the keyboard avoidance.

I found a workaround that could be helpful depending on requirements. I hide the bottom button whenever a user is entering text. Since you can't see the button anyway where the keyboard is up. It is not super elegant. But hopefully in future versions of SwiftUI the .ignoresSafeArea(.keyboard) will work for this use case.

struct ContentView: View {

    @State var text = ""
    @FocusState var isFieldFocused: Bool

    var body: some View {
        VStack {
            ScrollView {
                TextField("Testing", text: $text)
                    .focused($isFieldFocused)
            }
            if !isFieldFocused {
                Button("Some title", action: {})
            }
        }
    }
}

Upvotes: 1

Related Questions