Skip to content

Instantly share code, notes, and snippets.

@indyfromoz
Forked from noahsark769/swiftui-utils.swift
Created July 28, 2020 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indyfromoz/9a0831f5da1e81e153b66978d5035335 to your computer and use it in GitHub Desktop.
Save indyfromoz/9a0831f5da1e81e153b66978d5035335 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ConditionalContent<TrueContent: View, FalseContent: View>: View {
let value: Bool
let trueContent: () -> TrueContent
let falseContent: () -> FalseContent
var body: some View {
if value {
return AnyView(trueContent())
} else {
return AnyView(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