1

我有一个包含按钮的视图。带有按钮的视图是从 forEach 循环创建的。出于某种原因,只有一些按钮可以点击,而其他按钮则不能。

父视图包含 NavigationView、NavigationView 内部的滚动视图、滚动视图内部的lazyVStack、lazyVStack 中的 forEachloop 以及包含按钮的子视图。

struct ContentView: View {

  let peoples:[Person] = Bundle.main.decode("data.json")

  var body: some View {
    let columns = [
      GridItem(.flexible(minimum: 300), spacing: 10)
    ]

    NavigationView {
      ScrollView(.vertical) {
        LazyVStack {
          ForEach(peoples, id: \.self) { person in
            PersonView(name: person.Name, age: person.Age)
          }
        }
        .navigationTitle("A list of people")
        .navigationViewStyle(DefaultNavigationViewStyle())
        .padding()
      }
    }
  }
}

子视图如下。我怀疑滚动视图正在窃取用户输入,但我不确定为什么或如何克服它。有些按钮是可粘贴的,有些则不是。

struct PersonView: View {

  @Environment(\.colorScheme) var colorScheme

  var name: String
  var age: Int

  var body: some View {
    VStack(alignment:.leading) {
      Image("randoPerson")
        .resizable()
        .scaledToFill()
        .frame(minWidth: nil, idealWidth: nil,
               maxWidth: UIScreen.main.bounds.width, minHeight: nil,
               idealHeight: nil, maxHeight: 300, alignment: .center)
        .clipped()
      VStack(alignment: .leading, spacing: 6) {
        Text("name")
          .fontWeight(.heavy)
          .padding(.leading)

        Text("Age \(age)")
          .foregroundColor(Color.gray)
          .padding([.leading,.bottom])


        Button(action: { print("I was tapped") }) {
          HStack {
            Image(systemName: "message.fill")
              .font(.title)
              .foregroundColor(.white)
              .padding(.leading)

            Text("Message them")
              .font(.subheadline)
              .foregroundColor(.white)
              .padding()
          }
          .background(Color.blue)
        }
        .padding()
      }
      .background(Color(UIColor.systemBackground).cornerRadius(15))
      .shadow(color:colorScheme == .dark
                ? Color.white.opacity(0.2)
                : Color.black.opacity(0.2),
              radius: 7, x: 0, y: 2)
    }
  }
}
4

1 回答 1

0

要解决此问题,您可以将id: UUID关联添加到 a并在, 内部使用其 IDPerson进行迭代。PersonForEach

您还会注意到我将值添加为小写以遵守 Swift 约定。

struct Person {

  let id: UUID // Add this value
  var name: String
  var age: Int
}

所以这是带有id替换的 ContentView \.self

struct ContentView: View {

  let peoples: [Person] = Bundle.main.decode("data.json")

  var body: some View {
    NavigationView {
      ScrollView(.vertical) {
        LazyVStack {
          ForEach(peoples, id: \.id) { person in  // id replace \.self here
            PersonView(name: person.name, age: person.age)  // removed uppercase
          }
        }
        .navigationTitle("A list of people")
        .navigationViewStyle(DefaultNavigationViewStyle())
        .padding()
      }
    }
  }
}
于 2021-03-29T08:24:23.657 回答