微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MacOS 上的 SwiftUI 单击行为

如何解决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 举报,一经查实,本站将立刻删除。