Prevent the TextField from moving up with the keyboard in SwiftUI
In this tutorial, we will see how to prevent the TextField from moving up with the keyboard in SwiftUI.
We can use the ignoresSafeArea()
modifier to prevent the TextField from moving up when the keyboard appears.
Syntax
.ignoresSafeArea(.keyboard, edges: .bottom)
The above code will indicate SwiftUI to ignore the safe area adjustment for the bottom edge when the keyboard appears.
Now, have a look at the example below.
import SwiftUI struct ContentView: View { @State private var textInput: String = "" var body: some View { VStack { Spacer() TextField("Enter text here", text: $textInput) .padding() .textFieldStyle(RoundedBorderTextFieldStyle()) Text("You entered: \(textInput)") .padding() Spacer() } .padding() .ignoresSafeArea(.keyboard, edges: .bottom) //Prevents the TextField from moving up with the keyboard } }
In the above program, I have used VStack
to align the contents vertically, inside the VStack
I have created a TextField
and Text
view.
I have used Spacer()
before and after the TextField
to make the TextField stay center when there is no keyboard present, and it won’t be pushed off when the keyboard apperas.
Then, I have applied the ignoresSafeArea()
on the VStack
to prevent the TextField
from moving up with the keyboard.
Output:
Leave a Reply