[英]How can I make a side bar in SwiftUI in navigationstack
I am trying to make a sidebar in swiftUI that is triggered in and out from the side with a button我正在尝试在 swiftUI 中制作一个侧边栏,它是用一个按钮从侧面触发的
I have been able to make it pop in and out from the bottom using a side modifier like this我已经能够使用这样的侧面修饰符使其从底部弹出和弹出
struct sideBarExample: View {
@State var showSideBar = false
var mainView: some View{
Rectangle()
.foregroundColor(.blue)
.overlay(Text("Main View"))
}
var sideBar: some View{
Rectangle()
.foregroundColor(.green)
.overlay(Text("side bar"))
}
var body: some View {
NavigationStack{
mainView
.sheet(isPresented: $showSideBar, content: {
sideBar
})
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button {
showSideBar.toggle()
} label: {
Image(systemName: "sidebar.left")
}
}
}
}
}
}
But ideally it should be from the side但理想情况下应该是从侧面
For iPhone you have to build your own sidebar, just overlay it in a ZStack
and animate in with .transition
.对于 iPhone,您必须构建自己的侧边栏,只需将其覆盖在
ZStack
中并使用.transition
进行动画处理。
struct ContentView: View {
@State private var showSideBar = false
var mainView: some View{
Rectangle()
.foregroundColor(.gray)
.overlay(Text("Main View"))
}
var sideBar: some View{
Rectangle()
.foregroundColor(.green)
.overlay(Text("side bar"))
.frame(width: 200)
}
var body: some View {
NavigationStack{
ZStack(alignment: .leading) {
mainView
if showSideBar {
sideBar
.transition(.move(edge: .leading))
}
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button {
withAnimation {
showSideBar.toggle()
}
} label: {
Image(systemName: "sidebar.left")
}
}
}
}
}
}
You can use the offset
view modifier to move the sidebar around您可以使用
offset
视图修改器来移动侧边栏
Here is an example这是一个例子
struct SideBarExample: View {
@State var showSideBar = false
var mainView: some View{
Rectangle()
.foregroundColor(.blue)
.overlay(Text("Main View"))
}
var sideBar: some View{
HStack{
Rectangle()
.foregroundColor(.green)
.overlay(Text("side bar"))
.frame(width:250)
Spacer()
}
}
var body: some View {
NavigationStack{
ZStack{
mainView
sideBar
.offset(CGSize(width: showSideBar ? 0:-250, height: 0))
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button {
withAnimation {
showSideBar.toggle()
}
} label: {
Image(systemName: "sidebar.left")
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.