Move Textfield Up When the Keyboard Has Appeared in Swiftui

SwiftUI Textfield Padding when Keyboard is in view

If you are using iOS 14+ with scrollview or have the option to use scrollview.

https://developer.apple.com/documentation/swiftui/scrollviewproxy https://developer.apple.com/documentation/swiftui/scrollviewreader

Below might help

    ScrollViewReader { (proxy: ScrollViewProxy) in
ScrollView {
view1().frame(height: 200)
view2().frame(height: 200)

view3() <-----this has textfields
.onTapGesture {
proxy.scrollTo(1, anchor: .center)
}
.id(1)

view4() <-----this has text editor
.onTapGesture {
proxy.scrollTo(2, anchor: .center)
}
.id(2)

view5().frame(height: 200)
view6().frame(height: 200)
submtButton().frame(height: 200)
}
}

imp part from above is

     anyView().onTapGesture {
proxy.scrollTo(_ID, anchor: .center)
}.id(_ID)

Hope this helps someone :)

Focused TextField ends up covered by the keyboard in SwiftUI

Chaning two+ states in one closure (when they are related somehow or affects one area) are handled not very good (or not reliable). The fix is to separate them in different handlers.

Tested with Xcode 13.3 / iOS 15.4

demo

Here is main part:

VStack {
// ... other code

.onSubmit {
// update state here !!
if (i + 1) < inputsValues.count {
focusedInput = i + 1
} else {
focusedInput = nil
}
}
}
}
.onChange(of: focusedInput) {
// react on state change here !!
proxy.scrollTo($0)
}

Complete test module is here

iOS 14 SwiftUI Keyboard lifts view automatically

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



Related Topics



Leave a reply



Submit