Skip to content

Instantly share code, notes, and snippets.

@mezhevikin
Created August 21, 2023 07:34
Show Gist options
  • Save mezhevikin/e0652bfc721e1dffcee512137461a1e9 to your computer and use it in GitHub Desktop.
Save mezhevikin/e0652bfc721e1dffcee512137461a1e9 to your computer and use it in GitHub Desktop.
TouchDownButton.swift
import SwiftUI
struct ContentView: View {
var body: some View {
TouchDownButton(action: {
print("touchDown")
}) {
Text("Test")
}.onLongPressGesture {
print("longPress")
}
}
}
struct TouchDownButton<Content: View>: View {
let action: () -> Void
let content: Content
init(
action: @escaping () -> Void,
@ViewBuilder content: () -> Content
) {
self.action = action
self.content = content()
}
var body: some View {
content.background(
UITouchDownButton(action: action)
)
}
}
struct UITouchDownButton: UIViewRepresentable {
let action: () -> Void
func makeUIView(context: Context) -> UIControl {
let control = UIControl()
control.addTarget(
context.coordinator,
action: #selector(Coordinator.touchDown),
for: .touchDown
)
return control
}
func updateUIView(_ uiView: UIControl, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
let parent: UITouchDownButton
init(_ parent: UITouchDownButton) {
self.parent = parent
}
@objc func touchDown() {
parent.action()
}
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment