带有折叠按钮的 SwiftUI 侧边栏

问题描述 投票:0回答:1

我尝试将“添加”按钮添加到

NavigationSplitView
应用程序的
macos
内的侧边栏,与 Xcode 窗口中的相同。 在侧边栏视图中使用此代码确实会在视图顶部创建按钮,但折叠侧边栏时它不会隐藏。

.toolbar {
        ToolbarItem(placement: .primaryAction) {
            Button(action: addUser) {
                Label("Create New User",
                      systemImage: "person.crop.circle.badge.plus")
            }
            .help("New User")
        }

如何在底部创建一个侧边栏视图特定按钮,该按钮粘在侧边栏上并在侧边栏折叠时隐藏? 谢谢!

macos button swiftui sidebar
1个回答
0
投票

在 macOS 的 SwiftUI 中,可用于定位工具栏项目的

ToolbarItemPlacement
选项均不对应于侧边栏的底部。

但是,您可以通过在视图中放置控件来实现类似的效果。虽然您可以将它们放置在 ZStack 或 VStack 中,但另一种(有些人可能会说更惯用)方法是使用

.safeAreaInset
。例如:

struct ContentView: View {
    var body: some View {
        NavigationSplitView {
            List {
                ForEach(1..<100, id: \.self) { i in
                    Text("Sidebar Item \(i)")
                }
            }
            .safeAreaInset(edge: .bottom) {
                HStack {
                    Button("Add", systemImage: "plus") { }
                    Spacer()
                }
                .controlSize(.small)
                .labelStyle(.iconOnly)
                .padding(8)
            }
        } detail: {
            Text("Detail")
        }
    }
}

An example of a sidebar with a bottom bar using .safeAreaInset

© www.soinside.com 2019 - 2024. All rights reserved.