前端
MacOS使用SwiftUI实现Sidebar侧边栏
  • By刘立博
  • 2021-10-24 19:57:45
  • 2315人已阅读

创建子视图

创建3个待切换的视图(SubView1、2、3),分别输出字符串SubView1、2、3

import SwiftUI

struct SubView1: View {
    var body: some View {
        Text("SubView1")
    }
}

创建侧边栏

编辑ContentView通过在NavigationView中内嵌一个NavigationLink列表,即可实现左侧菜单样式,其中destination属性为点击后右侧打开的子页面

struct ContentView: View {
    var body: some View {
        
        NavigationView {
            
            List{
                NavigationLink(destination: SubView1()){
                    Label("subView1",systemImage: "ruler").font(.title3)
                }.padding()
                
                NavigationLink(destination: SubView2()){
                    Label("subView1",systemImage: "ruler").font(.title3)
                }.padding()
                
                NavigationLink(destination: SubView3()){
                    Label("subView1",systemImage: "ruler").font(.title3)
                }.padding()
            }
        }
        .listStyle(SidebarListStyle())
        .navigationTitle(LocalizedStringKey("Sidebar"))
    }
}

效果如下: