0

contextMenu出现时,我试图延迟,因为我有一个拖动手势,当我尝试拖动时会出现这种意外延迟

…
Text(exampleText)
  .contextMenu
  {
    delay()

    // Menus here
  }
  .gesture(
    DragGesture()
      .onEnded(
        { end in
          switch exampleTextAlignment
          {
            case .leading:
              if end.translation.width > 0
              {
                exampleTextAlignment = .center
              }
            case .center:
            if end.translation.width < 0
              {
                exampleTextAlignment = .leading
              }
            else if end.translation.width > 0
              {
                exampleTextAlignment = .trailing
              }
            case .trailing:
              if end.translation.width < 0
              {
                exampleTextAlignment = .center
              }
          }
        }
      )
    )
…

…其中 delay() 是:

…
private func delay() async {
        try? await Task.sleep(nanoseconds: UInt64(secondsHere * Double(NSEC_PER_SEC)))
        hasTimeElapsed = true
    }
…

预期结果

Xcode v.13.2iOS v.15.2

4

1 回答 1

0

这对我来说非常有效:

struct ContentView: View {
    
    let exampleText = "I'm trying to delay when the contextMenu appears because I have a drag gesture which causes me this view when trying to drag with some kind of accidental delay."
    
    @State private var exampleTextAlignment: TextAlignment = .center
    
    var body: some View {
        VStack {
            Text(exampleText)
                .multilineTextAlignment(exampleTextAlignment)
                .contextMenu {
                    // Menus here
                    Button("Test") {}
                }
                .gesture(DragGesture()
                            .onEnded { end in
                    switch exampleTextAlignment
                    {
                    case .leading:
                        if end.translation.width > 0 {
                            exampleTextAlignment = .center
                            //  onContextMenuAlignment = .top
                        }
                    case .center:
                        if end.translation.width < 0 {
                            exampleTextAlignment = .leading
                            //  onContextMenuAlignment = .topLeading
                        }
                        else if end.translation.width > 0 {
                            exampleTextAlignment = .trailing
                            //   onContextMenuAlignment = .topTrailing
                        }
                    case .trailing:
                        if end.translation.width < 0 {
                            exampleTextAlignment = .center
                            //   onContextMenuAlignment = .top
                        }
                    default: break
                    }
                }
            )
        }
        .padding()
    }
}
于 2022-02-21T21:50:21.870 回答