Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move TextEditor (in List) up when the keyboard appeared in SwiftUI

I have a SwiftUI List with a TextEditor as the last row. In SwiftUI text fields automatically move up above the keyboard. But unfortunately when the TextEditor is in a List it doesn't seem to work.

There has been a lot of good solutions for this when using a TextField Ex:- Move TextField up when the keyboard has appeared in SwiftUI. But none of them seem to work when using TextEditor.


struct ContentView: View {

    @State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit","Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]

    @State private var newItemText : String = ""


    var body: some View {
        ZStack(alignment: Alignment.bottom) {
            List{
                 ForEach(items, id: \.self) { 
                     Text("\($0)")
                 }
                 TextEditor(text: $newItemText)
            }
            
        }
    }
}

like image 475
unknown Avatar asked Oct 16 '25 20:10

unknown


1 Answers

It seems that the view does automatically resizes so that it's above the keyboard. All that needs to be done is scrolling to the last row of the list.

struct ContentView: View {

    @State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit","Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]

    @State private var newItemText : String = ""


    var body: some View {
      ScrollViewReader { (proxy: ScrollViewProxy) in
        ZStack(alignment: Alignment.bottom) {
            List{
                 ForEach(items, id: \.self) { 
                     Text("\($0)")
                 }
                 TextEditor(text: $newItemText)
                    .onChange(of: newItemText) { newValue in
                          proxy.scrollTo(999, anchor: .bottom)
                   }.id(999)
            }
            
        }
      }
    }
}
like image 51
unknown Avatar answered Oct 18 '25 14:10

unknown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!