Search code examples
swiftkeyboardswiftuitextfieldios14

iOS 14 SwiftUI Keyboard lifts view automatically


I am using TextField in my view and when it becomes the first responder, it lefts the view as shown in the below GIF.

Is there any way I can get rid of this behavior?

enter image description here

Here is my code

NavigationView(content: {
    ZStack{
        MyTabView(selectedIndex: self.$index)
            .view(item: self.item1) {
                NewView(title: "Hello1").navigationBarTitle("")
                    .navigationBarHidden(true)
            }
            .view(item: self.item2) {
                NewView(title: "Hello2").navigationBarTitle("")
                    .navigationBarHidden(true)
            }
            .view(item: self.item3) {
                NewView(title: "Hello3").navigationBarTitle("")
                    .navigationBarHidden(true)
            }
    }.navigationBarHidden(true)
    .navigationBarTitle("")
}).ignoresSafeArea(.keyboard, edges: .bottom)

// New View

struct NewView:View {
    @State var text:String = ""
    var title:String
    var body: some View {
        VStack {
            Spacer()
            Text("Hello")
            TextField(title, text: self.$text)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            
        }.padding()
        .onAppear {
            debugPrint("OnApper \(self.title)")
        }
    }
}

Solution

  • You should apply the modifier on the ZStack, NOT the NavigationView

    NavigationView(content: {
        ZStack{
            ,,,
        }.navigationBarHidden(true)
        .navigationBarTitle("")
        .ignoresSafeArea(.keyboard, edges: .bottom) // <- This line moved up
    })
    

    Full working example:

    struct ContentView: View {
        @State var text = ""
        var body: some View {
            VStack{
                Spacer()
                Text("Hello, World")
                TextField("Tap to test keyboard ignoring", text: $text)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            .padding()
            .ignoresSafeArea(.keyboard, edges: .bottom)
        }
    }
    

    Demo