【问题标题】:How to Handle screen touch events with SwiftUI?如何使用 SwiftUI 处理屏幕触摸事件?
【发布时间】:2019-07-08 08:29:53
【问题描述】:

使用 UIKit 时,我在 UIView 或 UIViewController 中处理。

func touchesBegan(_ touches: Set, 有事件:UIEvent?)

如何使用 SwiftUI 处理触摸事件?

【问题讨论】:

标签: ios swiftui


【解决方案1】:

最简单的事情是添加一个 DragGesture。 Check outDragGesture.Value 了解您有哪些可用信息。

Circle()
    .gesture(
        DragGesture(minimumDistance: 5, coordinateSpace: .global)
            .onChanged { value in
              self.dragLocation = value.location
            }
            .onEnded { _ in
              self.dragLocation = .zero
            }
    )

您可以使用minimumDistance: 0 来获得立即开始更新的手势,类似于UIKit 中的touchesBegan(...)

【讨论】:

    【解决方案2】:

    作为另一种方式,我们可以创建自定义按钮。 SwiftUI 提供了 ButtonStyle、PrimitiveButtonStyle 等。

    https://developer.apple.com/documentation/swiftui/buttonstyle

    其实Button并没有自己创建标签,Button有Style,并且委托创建标签给Style。

    所以,Style 有makeBody 方法,我们可以得到一个配置对象。 该对象具有从外部传递的标签和isPressed 标志。

    isPressed 将更改为 touchDown 和 touchUpInside 事件。

    我已经创建了自定义按钮样式。当组件被触摸时,它会添加一个覆盖。

    https://www.notion.so/muukii/Create-custom-highlight-component-Like-subclassing-UIControl-a4e231ffa3624dfda96141a2f60588f1

    示例代码

    struct OverlayButton<Content: View>: View {
    
      private let content: Content
    
      init(
        @ViewBuilder _ content: () -> Content
      ) {
        self.content = content()
      }
    
      var body: some View {
        Button(action: {}) { content }
          .buttonStyle(_ButtonStyle())    
      }
    
      private struct _ButtonStyle: ButtonStyle {
    
        func makeBody(configuration: Self.Configuration) -> AnyView {
          if configuration.isPressed {
            return AnyView(
              configuration.label
                .background(Color(white: 0.96))
            )
          } else {
            return AnyView(
              configuration.label
                .background(Color(white: 1, opacity: 0.0001))
            )
          }
        }
      }
    
    }
    

    我希望这是你的想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2015-12-05
      相关资源
      最近更新 更多