4

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)
            }
            
        }
    }
}

unknown
  • 788
  • 9
  • 24
  • You need to move the `ZStack` up, not just the `TextEditor`. Try the other solutions with that in mind. – Yrb Nov 19 '21 at 13:26
  • Tried that it doesn't seem to help. Does that work for you? – unknown Nov 19 '21 at 13:50
  • I didn't work through the answer, which is why I didn't post it. So, you are saying you put a `.frame` on your `ZStack` and a `GeometryReader` around it, and reduced the height of the `ZStack` by the keyboard's height, and it didn't shrink? – Yrb Nov 19 '21 at 13:58
  • Well it does shrink the height of the `ZStack`, but the list doesn't scroll to the bottom so the last item is still not visible. – unknown Nov 19 '21 at 14:23
  • 1
    You never told the list to do that. That is not automatic with a keyboard coming up. Search on `scrollTo`. – Yrb Nov 19 '21 at 14:36

1 Answers1

2

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)
            }
            
        }
      }
    }
}
unknown
  • 788
  • 9
  • 24