List or a ForEach from a binding: keyboard issue

Hello developers !

I've created a List or a ForEach from a binding where there are TextFields or TextEditors inside. When I go to fill in the text, the keyboard dismisses after one char is typed in !

My need is to be able to add textfields as much as required.

Please have a look to this code

import SwiftUI

struct ContentView: View {
    
    @State private var messages = ["Hello 1","Hello 2","Hello 3"]
    
    var body: some View {
        VStack(alignment: .leading) {

            List($messages, id: \.self) { $msg in
                TextEditor(text: $msg)
            }
            
            ForEach($messages, id: \.self) { $msg in
                VStack{
                    TextEditor(text: $msg)
                }
                .contextMenu{
                    Button(role: .destructive, action: {
                        messages = messages.filter {$0 != msg}
                        
                    }, label:{
                        Text("Delete entry")
                    })
                }
            }
            
            Button(action: {
                messages.append("-")
            }
            , label: {
                Text("Add a row")
            })
        }
        .background(.black)
        .padding()
    }
}


#Preview {
    ContentView()
}

I'm using iOS 17.4 and Xcode 15.3 Thanks !

Answered by Claude31 in 787908022

Did you get any answer to your FB ?

I may have found with focusField

Declare

    @FocusState private var focusedField: String?

Then in TextField

                TextField("", text: $msg)
                    .focused($focusedField, equals: msg)
                    .task {
                      self.focusedField = msg
                    }

I tested and reproduced the problem, in simulator and on device..

Problem seems to be the association of List and TextEditor ; when typing, List cells or ForEach cells are resized, forcing keyboard to hide.

Problem is not TextEditor itself, as this works properly if alone:

struct ContentView: View {
    
    @State private var msg = "Hello"

    var body: some View {
        TextEditor(text: $msg)
   }
}

Note: same problem with TextField:

            List($messages, id: \.self) { $msg in
                TextField("A", text: $msg)
            }

You may file a bug report.

Hello Thanks for your answer. I did a feedback, I will report a bug then.

Bug reported : FB13714612

Accepted Answer

Did you get any answer to your FB ?

I may have found with focusField

Declare

    @FocusState private var focusedField: String?

Then in TextField

                TextField("", text: $msg)
                    .focused($focusedField, equals: msg)
                    .task {
                      self.focusedField = msg
                    }

Yes it works with this focusfield. I got no feedback for your information.

List or a ForEach from a binding: keyboard issue
 
 
Q