Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SwiftUI utils I use in most projects. See https://twitter.com/noahsark769/status/1287751020131561474?s=20
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
You can’t perform that action at this time.