SideBarStack Swift文件

  1. import SwiftUI
  2. struct SideBarStack<SidebarContent: View, Content: View>: View {
  3. let sidebarContent: SidebarContent
  4. let mainContent: Content
  5. let sidebarWidth: CGFloat
  6. @Binding var showSidebar: Bool
  7. init(sidebarWidth: CGFloat, showSidebar: Binding<Bool>, @ViewBuilder sidebar: ()->SidebarContent, @ViewBuilder content: ()->Content) {
  8. self.sidebarWidth = sidebarWidth
  9. self._showSidebar = showSidebar
  10. sidebarContent = sidebar()
  11. mainContent = content()
  12. }
  13. var body: some View {
  14. ZStack(alignment: .leading) {
  15. sidebarContent
  16. .frame(width: sidebarWidth, alignment: .center)
  17. .offset(x: showSidebar ? 0 : -1 * sidebarWidth, y: 0)
  18. .animation(Animation.easeInOut.speed(2))
  19. mainContent
  20. .overlay(
  21. Group {
  22. if showSidebar {
  23. Color.white
  24. .opacity(showSidebar ? 0.01 : 0)
  25. .onTapGesture {
  26. self.showSidebar = false
  27. }
  28. } else {
  29. Color.clear
  30. .opacity(showSidebar ? 0 : 0)
  31. .onTapGesture {
  32. self.showSidebar = false
  33. }
  34. }
  35. }
  36. )
  37. .offset(x: showSidebar ? sidebarWidth : 0, y: 0)
  38. .animation(Animation.easeInOut.speed(2))
  39. }
  40. }
  41. }

用法

  1. SideBarStack(sidebarWidth: CGFloat, showSidebar: isShowBool){
  2. content
  3. }
  4. //isShowBool建议使用EnvironmentObject,可跨视图属性