Last active
August 29, 2021 20:40
-
-
Save noahsark769/42dbc1e38e6345997d0493692fd3b70e to your computer and use it in GitHub Desktop.
SwiftUI utils I use in most projects. See https://twitter.com/noahsark769/status/1287751020131561474?s=20
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
// Note: There are some issues with using these modifiers inside of ButtonStyles on macOS. Please see https://twitter.com/noahsark769/status/1288256379640139776?s=20 for more info. | |
struct ConditionalContent<TrueContent: View, FalseContent: View>: View { | |
let value: Bool | |
let trueContent: () -> TrueContent | |
let falseContent: () -> FalseContent | |
@ViewBuilder var body: some View { | |
if value { | |
trueContent() | |
} else { | |
falseContent() | |
} | |
} | |
} | |
extension View { | |
func conditionally<TrueContent: View>( | |
_ value: Bool, | |
content: @escaping (Self) -> TrueContent | |
) -> ConditionalContent<TrueContent, Self> { | |
return ConditionalContent( | |
value: value, | |
trueContent: { content(self) }, | |
falseContent: { self } | |
) | |
} | |
} | |
struct HoverView<Content: View>: View { | |
let content: (Bool) -> Content | |
@State var isHovering: Bool = false | |
var body: some View { | |
return content(isHovering).onHover { hovering in | |
self.isHovering = hovering | |
} | |
} | |
} | |
extension View { | |
func hoverContent<TransformedContent>( | |
_ content: @escaping (Self) -> TransformedContent | |
) -> HoverView<ConditionalContent<TransformedContent, Self>> { | |
return HoverView { isHovering in | |
self.conditionally(isHovering, content: content) | |
} | |
} | |
} | |
extension View { | |
func cursor(_ cursor: NSCursor) -> some View { | |
return self.onHover { isInside in | |
if isInside { | |
cursor.push() | |
} else { | |
NSCursor.pop() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment