【问题标题】:SwiftUI macOS double tap list itemSwiftUI macOS 双击列表项
【发布时间】:2020-10-10 13:02:09
【问题描述】:

我想要一个拆分视图,其中包含可双击的详细视图中的项目。我创建了以下示例来展示我的问题:

struct ContentView: View {
var body: some View {
    NavigationView {
        List(["Hello", "World"]) { str in
            NavigationLink(destination: DetailView(title: str)) {
                Text(str)
            }
        }
    }.frame(minWidth: 300, minHeight: 300)
  }
}

struct DetailView: View {

    let title: String
    @State var isShowingAlert = false

    var body: some View {
        VStack {
            Text(title)
            List(["This", "is", "SwiftUI", "!"]) { str in
                Text(str).onTapGesture(count: 2) {
                self.isShowingAlert = true
            }.alert(isPresented: self.$isShowingAlert) { () -> Alert in
                Alert(title: Text(str), message: Text("This is a hello message"), dismissButton: Alert.Button.default(Text("Ok")))
            }
        }
    }.frame(minWidth: 200)
  }
}

所以 splitview 部分按预期工作。但是当我双击一个行项目时,它总是向我显示两次警报,内容如下。所以我点击哪个项目并不重要。它总是向我显示警报中的第一项和第二项。关闭标题为“This”的第一个警报后,第二个标题显示为“is”:

第一个警报:

第二个警报:

为什么双击会显示两个警报?即使我选择列表中的最后一项,为什么总是前两项?有什么建议或解决方案吗?非常感谢:)

【问题讨论】:

    标签: swift macos swiftui


    【解决方案1】:

    您可以通过将一个警报附加到每个列表行来创建许多警报,并通过切换一种状态来激活所有警报...后果实际上是不可预测的。

    相反,它应该只是一个由自己的状态管理的警报。所以这是可能的解决方案:

    struct DetailView: View {
    
        let title: String
        @State private var selectedItem: String = ""
        @State private var isShowingAlert = false
    
        var body: some View {
            VStack {
                Text(title)
                List(["This", "is", "SwiftUI", "!"]) { str in
                    Text(str).onTapGesture(count: 2) {
                        self.selectedItem = str        // << store clicked raw item
                        self.isShowingAlert = true     // << activate alert !!
                    }
                }
                .alert(isPresented: self.$isShowingAlert) { // << attach here !!
                    Alert(title: Text(self.selectedItem), message: Text("This is a hello message"), dismissButton: Alert.Button.default(Text("Ok")))
                }
            }.frame(minWidth: 200)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多