Skip to content

Commit

Permalink
👆 HoverView click and action passing
Browse files Browse the repository at this point in the history
  • Loading branch information
benlmyers committed Aug 10, 2022
1 parent de48592 commit d7480bf
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions Sources/ShinySwiftUI/Views/HoverView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,52 @@

import SwiftUI

@available(macOS 11.0, *)
public struct HoverView<Content>: View where Content: View {

// MARK: - Public Wrapped Properties

/// The content to display.
@ViewBuilder public let content: (Bool) -> Content
@ViewBuilder public let content: (Bool, Bool) -> Content

/// Whether the view is hovered.
@State public var hover: Bool = false
/// Whether the view is clicked.
@State public var clicked: Bool = false

// MARK: - Public Properties

/// The action to perform on click.
public let action: () -> Void

// MARK: - Public Body View

public var body: some View {
content(hover).onHover { hover = $0 }
Button(action: action) {
content(hover, clicked).onHover { hover = $0 }
}
.buttonStyle(HoverButtonStyle(pressed: $clicked))
}

// MARK: - Public Initalizers

public init(content: @escaping (Bool) -> Content) {
self.content = content
public init(action: @escaping () -> Void = {}, content c: @escaping (Bool, Bool) -> Content) {
self.action = action
self.content = c
}

public init(action: @escaping () -> Void = {}, content c: @escaping (Bool) -> Content) {
self.action = action
self.content = { (hover: Bool, click: Bool) in
return c(hover)
}
}
}

@available(macOS 11.0, *)
fileprivate struct HoverButtonStyle: ButtonStyle {
let pressed: Binding<Bool>
func makeBody(configuration: Configuration) -> some View {
configuration.label.onChange(of: configuration.isPressed) { val in pressed.wrappedValue = val }
}
}

0 comments on commit d7480bf

Please sign in to comment.