Skip to content

Instantly share code, notes, and snippets.

@rnmp
Last active October 15, 2024 19:55
Show Gist options
  • Save rnmp/61ae2ab3ff06db8a2150f1c8678fdda5 to your computer and use it in GitHub Desktop.
Save rnmp/61ae2ab3ff06db8a2150f1c8678fdda5 to your computer and use it in GitHub Desktop.
Sliding sidebar (hover to show) in SwiftUI. See more or less how I built it: https://youtu.be/FYrNgz2xADc
import SwiftUI
struct Sidebar<Content: View>: View {
@State var visible: Bool = false
var content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
ZStack(alignment: .leading) {
HStack(spacing: 0) {
Spacer()
.frame(width: 16)
RoundedRectangle(cornerRadius: 8)
.fill(.black.opacity(!visible ? 0.2 : 0))
.offset(x: !visible ? 0 : -20)
.frame(width: 4, height: 40)
Spacer()
}
.frame(maxWidth: 80, maxHeight: 500)
ZStack {
content()
.frame(width: 200)
}
.frame(maxWidth: visible ? 200 : 100, maxHeight: visible ? 500 : 600)
.background(
RoundedRectangle(cornerRadius: 16).fill(Color.white)
.shadow(color: .black.opacity(0.1), radius: 12, x: 0, y: 1)
.shadow(color: .black.opacity(0.2), radius: 1)
)
.offset(x: visible ? 20 : -100)
.opacity(visible ? 1 : 0)
}
.frame(maxHeight: .infinity)
.onHover { next in
withAnimation(.interactiveSpring(duration: 0.2)) {
visible = next
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment