Published on

Navigation in SwiftUI

Authors

Navigation

Enable people to move between different parts of app's view hierarchy within a scene.

Overview

Use navigaiton containers to provide structure to your app's user interface, enabling people to easily move among the parts of your app.

一种两列视图或者三列视图显示的视图,在前面的列选择可控制后面的列的显示

NavigationSplitView
NavigationSplitView

版本限制

iOS16.0+ macOS 13.0+ Mac Catalyst 16.0+ tvOS 16.0+ watchOS 9.0+ visionOS 1.0+ Beta

如何定义

struct NavigationSplitView<Sidebar, Content, Detail> where Sidebar : View, Contetn : View, Detail : View

用法

创建一个 two-column navigation split view, 使用 ```init(sidebar: detail:) 来初始化

@State private var employeeIds: Set<Employee.ID> = []

var body: some View {
    NavigationSplitView {
        List(model.employees, selection: $employeeIds) { employee in 
            Text(employee.name)
        } detail: {
            EmployeeDetail(for: employeeIds)
        }
    }
}

在这段代码中,第一列Sidebar是用List来返回,在List的selection中是传入的一个employeeIds参数,这时需要保证是唯一标识,这各UIKit/APPKit中的UITableView采用的Indexpath标记不同,这里会直接使用DataSource Model中的唯一标识,这就要要求我们数据必须遵循Identiable协议

Control column visibility 如何控制列是否可见

Collapsed split views 折叠的拆分视图

Customize a split view

wwdc2022 The SwiftUI cookbook for navigation