Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

macos

ios

swiftui

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"))
        }
    }
}
like image 249
Tom Kraina Avatar asked Jun 24 '19 08:06

Tom Kraina


1 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.

like image 194
Anton Avatar answered Sep 26 '22 06:09

Anton