Skip to content

Instantly share code, notes, and snippets.

@gewill
Created February 13, 2023 15:21
Show Gist options
  • Save gewill/5b1dfa4cd7a8e6a60865f80aa4680d84 to your computer and use it in GitHub Desktop.
Save gewill/5b1dfa4cd7a8e6a60865f80aa4680d84 to your computer and use it in GitHub Desktop.
LinkButton: show NavigationLink as a button in SwiftUI
import SwiftUI
/// https://stackoverflow.com/a/62853420
struct LinkButton<Destination: View, Label: View>: View {
let destination: Destination
let label: Label
let action: () -> Void
@State private var isActive = false
init(action: @escaping () -> Void, @ViewBuilder destination: @escaping () -> Destination, @ViewBuilder label: @escaping () -> Label) {
self.action = action
self.destination = destination()
self.label = label()
}
var body: some View {
Button(action: {
$isActive.wrappedValue.toggle()
action()
}) {
label
}
.background(
NavigationLink(destination: destination, isActive: $isActive, label: {
EmptyView()
})
)
}
}
struct LinkButton_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
LinkButton {
print("Taped")
} destination: {
Text("detail")
} label: {
Text("Tap")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment