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

5
  • You need to move the ZStack up, not just the TextEditor. Try the other solutions with that in mind. Commented Nov 19, 2021 at 13:26
  • Tried that it doesn't seem to help. Does that work for you? Commented Nov 19, 2021 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? Commented Nov 19, 2021 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. Commented Nov 19, 2021 at 14:23
  • 1
    You never told the list to do that. That is not automatic with a keyboard coming up. Search on scrollTo. Commented Nov 19, 2021 at 14:36

1 Answer 1

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)
            }
            
        }
      }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

not working in iOS 15.5

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.