SwiftUI - TextField is disabled (not editable) when placed in List on macOS

Viewed 5502

TextField is disabled (not editable) when placed in List on macOS. When the same code is build for iOS and ran in Simulator, it works as expected.

Is this a bug, or am I missing something?

The code:

struct ContentView : View {

    @State private var text: String = ""

    var body: some View {
        VStack {
            List {
                // TextField is not editable when this code is ran on macOS
                TextField($text, placeholder: Text("Entry text"))
                Text("Entered text: \(text)")
            }
            // TextField is editable on both macOS as well as iOS
            TextField($text, placeholder: Text("Entry text"))
        }
    }
}
2 Answers

That's because the list is taking clicks to drive selection, which you're not using here. TextField becomes editable in the list on macOS only when the row in which it is housed has selection.

If you change your code to something like this

struct ContentView : View {
    @State private var text: String = "Hello"
    @State private var selection: Int? = nil
    var body: some View {
        VStack {
            List(selection: $selection) {
                ForEach(0..<5) { _ in
                    TextField(self.$text)
                }
            }
            TextField($text)
        }
    }
}

then run the code, the first click on the cell will cause it to get selected and the second click will cause the text field to receive focus.

Create the TextField using the following code

struct ContentView : View {
    @State private var helloText: String = "Hello"
    @State private var selection: Int? = nil
    var body: some View {
        VStack {
            List(selection: $selection) {
                ForEach(0..<5) { _ in
                    TextField(.constant(self.helloText), placeholder: Text("Entry text")).textFieldStyle(.roundedBorder)
                }
            }

        }
    }
}
Related