Skip to content

Instantly share code, notes, and snippets.

@ahtcx
Created February 28, 2024 02:45
Show Gist options
  • Save ahtcx/ec02cf9318b39b8927187952f976b1a8 to your computer and use it in GitHub Desktop.
Save ahtcx/ec02cf9318b39b8927187952f976b1a8 to your computer and use it in GitHub Desktop.
import SwiftUI
/// A custom button style designed specifically for use with `NavigationLink`.
///
/// `NavigationLinkButtonStyle` allows you to apply a `PrimitiveButtonStyle` to a `Button` within a `NavigationLink` in SwiftUI.
/// This style adds a forward chevron image to the button, providing a visual cue for navigation.
///
/// Example Usage:
/// ```swift
/// NavigationLink("Navigate") {
/// DetailView()
/// }
/// .buttonStyle(NavigationLinkButtonStyle())
/// ```
///
/// - Note: This style expects a `PrimitiveButtonStyle` to be provided during initialization. If none is provided,
/// it defaults to `DefaultButtonStyle`.
struct NavigationLinkButtonStyle<Style: PrimitiveButtonStyle>: PrimitiveButtonStyle {
/// The underlying button style applied to the button.
private let style: Style
/// Initializes the `NavigationLinkButtonStyle` with the provided button style.
///
/// - Parameter style: The button style to apply to the button.
init(_ style: Style) {
self.style = style
}
/// Creates a view that represents the body of a button with additional navigation chevron.
///
/// - Parameter configuration: The properties of the button.
/// - Returns: A view representing the styled button with a forward chevron.
func makeBody(configuration: Configuration) -> some View {
Button(role: configuration.role, action: configuration.trigger) {
configuration.label
Image(systemName: "chevron.forward")
}
.buttonStyle(style)
}
}
extension NavigationLinkButtonStyle where Style == DefaultButtonStyle {
/// Initializes the `NavigationLinkButtonStyle` with the default button style if none is provided.
init() {
self.style = .init()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment