【问题标题】:Is there a way to put buttons inside a SwiftUI cell view?有没有办法将按钮放在 SwiftUI 单元格视图中?
【发布时间】:2020-04-29 13:33:24
【问题描述】:

我有一个显示一些单元格的 SwiftUI 列表。我想在每个单元格内放置 3 个按钮。我希望用户能够在不选择单元格或触发其他按钮的情况下点击每个按钮。 当用户点击单元格时,我现在的代码会触发所有 3 个按钮。

struct ContentView: View {
    @State var names = ["Mohamed", "Ahmed", "Ali"]

    var body: some View {
        NavigationView {
            List {
                ForEach(names, id: \.self) { name in
                    NameCell(name: name)
                }
            }
            .navigationBarTitle("Names")
        }
    }
}

struct NameCell: View {
    let name: String

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text(name)
                .font(.headline)
            HStack {
                Button("Action1") { print("action 1 tapped") }
                Button("Action2") { print("action 2 tapped") }
                Button("Action3") { print("action 3 tapped") }
            }
        }
    }
}

【问题讨论】:

标签: swiftui


【解决方案1】:

它在SwiftUI 中看起来是一个错误,而在单元格内使用按钮整个区域都是可点击的。要解决此问题,您可以将Button 替换为Text,并将TapGesture 添加到Text

请尝试以下代码。

struct NameCell: View {

 ....            
      HStack(spacing: 10) {

          Text("Action1").onTapGesture {
                  print("action 1 tapped")
          }
          Text("Action2").onTapGesture {
                  print("action 2 tapped")
          }
          Text("Action3").onTapGesture {
                  print("action 3 tapped")
          }
    }
  ....
}

【讨论】:

    最近更新 更多