MacOS 上的 SwiftUI 单击行为

问题描述

在 MacOS 上的 SwiftUI 应用程序中,我在 Line 内的 List 视图中显示了一些项目。

预期行为是:

  • 点击、双击、按下 Line 中的特殊元素(在示例中 Text("X") 触发操作
  • 单击 Line 中的其他任意位置可选择 List 中的元素。
  • 双击 Line 中的其他任意位置会触发操作。

实际行为是:

  • Text("X") 的所有点击都正常。
  • 点击 Text("some Text") 不会选择元素
  • 点击 Line (Spacer()) 的右边缘选择元素
  • 双击 Text("some Text") 会触发操作
  • 双击 Line (Spacer()) 的右边缘不会触发操作

我有一个非常丑陋的解决方案(已注释掉):给 HStack 中的 Line 一个 Background,并手动设置选择,点击行为很好。
现在的问题是,将颜色设置为系统颜色。
有没有更好的解决方案?

这是我的代码

struct ContentView: View {
  @State var sel :Int? = nil
  var body: some View {
    List(selection: $sel) {
      Line(lineNr:0,selection: $sel).tag(0)
      Line(lineNr:1,selection: $sel).tag(1)
      Line(lineNr:2,selection: $sel).tag(2)
      Line(lineNr:3,selection: $sel).tag(3)
      Line(lineNr:4,selection: $sel).tag(4)
      Line(lineNr:5,selection: $sel).tag(5)
    }
  }
}

struct Line: View {
  @Environment(\.colorScheme) var colorScheme: ColorScheme
  var lineNr : Int
  @Binding var selection : Int?
  
  var body: some View {
    HStack {
      Text("X: ")
        .onTapGesture(count: 2,perform: { print("X double tapped") })
        .onTapGesture(count: 1,perform: { print("X tapped") })
        .onLongPressGesture { print ("X long-presses") }
      Text("some Text")
      Spacer()
    } 
    // ugly solution
    //.background( standardBackgoundColors()  )
    .onTapGesture(count: 2,perform: {
      print("Line double-clicked")
    // ugly solution
    // selection = lineNr
    })
    // ugly solution
    //.onTapGesture(count: 1,perform: {
    //  print("Line clicked")
    //  selection = lineNr
    //})
  }
  
  //Todo: find out the correct system colors
  func standardBackgoundColors()->Color{
    if (selection == lineNr) {
      return colorScheme == .light  ? Color(#colorLiteral(red: 0.8039215803,green: 0.8039215803,blue: 0.8039215803,alpha: 1)) : Color.black
    } else {
      return colorScheme == .light  ? Color.white : Color.black
    }
  }
}

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)