After using Xcode 12 for almost 3 months now, one thing I have consistently faced problem with is with the keyboard changing the orientation of the view. Although it is helpful sometimes as you don't have to change the offset manually based on the keyboard height, sometimes you just need more control over the look of your view.
Video
In the video below, the textfield moves up when the keyboard pops out, but it moves a bit too much. I have been trying to move the view with the login button sticking to the keyboard.
Code
VStack(spacing: 40) {
SignInView() // Consists 1 TextField, 1 SecureField and 1 Button
Rectangle()
.frame(width: screen.width, height: 2, alignment: .center)
.foregroundColor(Color(.systemGray5))
.padding(.top, 100)
HStack(spacing: 0.0) {
Text("Don't have an account? ")
Button(action: {
...
}) {
Text("Create one.")
.foregroundColor(Color("blue"))
}
}
.font(.system(size: 16, weight: .regular))
}
How I tried to resolve it.
I tried to nullify the auto-offset by applying an offset of keyboard.current
, where keyboard represents a KeyboardResponder
class, and subtracting the offset by 20 to give a bit of breathing area between keyboard and the login button. Unfortunately this didn't work. Even if it did, I'm sure that this is not the best solution.
@State private var keyboard = KeyboardResponder()
var body: some View {
VStack(spacing: 40) {
...
}
.offset(y: keyboard.currentHeight != 0 ? (keyboard.currentHeight - 20) : 0)
}