6

This problem is with SwiftUI for a macOS app (not iOS or catalyst), using Xcode 12.4 (SwiftUI 2). The problem is that editing of a TextField that is inside a List does not work well, in fact, it works so poorly that at first I thought I could not edit it at all.

This is the code, just as a simple example:

import SwiftUI

struct ContentView: View {
    @State var name1 = "Hans"
    @State var name2 = "E"
    @State var name3 = ""
    
    var body: some View {
        List {
            TextField("Name 1", text: $name1)
            TextField("Name 2", text: $name2)
            TextField("Name 3", text: $name3)
        }
        .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}

TextField with focus

And this is what I experience, trying to edit a field:

  • For a non-empty field, single-tap on the existing text: it works (after a small, but annoying, 0.5 second delay).
  • For a non-empty field, single-tap outside the existing text: nothing happens.
  • For an empty field ("Name 3"), single-tap anywhere in the field: it works (after a small delay).
  • Double-tap anywhere inside any field: nothing happens.

I hope this is not the intended behaviour. It is particularly problematic for a field that contains only a single character, making it difficult for the user (must tap exactly on the "E"). Am I doing something wrong here?

I noted the question Editable TextField in SwiftUI List, which is a bit similar, but that question reported the TextField to not work at all.

rene
  • 1,975
  • 21
  • 33
  • In your application, can you get away with not using `List` and just using a `ScrollView` instead? – jnpdx Mar 03 '21 at 17:49
  • 1
    @jnpdx Thank you for the suggestion! I can probably code around the problem in some way, as you suggest, but in this case I would really like to use what List has to offer. – rene Mar 03 '21 at 19:27
  • I think this post is much helpful: https://stackoverflow.com/q/70026160/115271 – Li Fumin Dec 12 '22 at 14:11

1 Answers1

-1

Found a solution.

import SwiftUI

struct ContentView: View {
    @State var name1 = "Hans"
    @State var name2 = "E"
    @State var name3 = ""
    
    var body: some View {
        List {}
          .overlay(VStack(spacing: 20){
              TextField("Name 1", text: $name1)
              TextField("Name 2", text: $name2)
              TextField("Name 3", text: $name3)
          })
          .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}
小弟调调
  • 1,315
  • 1
  • 17
  • 33
  • Sorry for being late with my reply to this. This solution does not solve the problem because it eliminates the functionality that the List is supposed to provide. For example, reduce the height of the window, and you will see the vertical scrolling no longer works. The example illustrates the problem with only 3 entries, but in general there could be many entries, so scrolling is essential. – rene Aug 24 '21 at 14:49