SwiftUI Divider 不影响其父级的大小

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

我在 macOS 应用程序中有这个 SwiftUI 侧边栏视图。

struct SidebarView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Things")
            
            // This divider is causing the sidebar to stretch to
            // its maximum width. What I want is for it to be as wide
            // as the current size of the sidebar without affecting
            // it's size.
            Divider()

            Spacer()

            Button("New Thing") {
                print("New Thing")
            }
        }
        .padding()
    }
}

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.green
            Text("Content View")
        }
    }
}

struct TestView: View {
    var body: some View {
        HSplitView {
            SidebarView()
                .frame(minWidth: 200)
            ContentView()
                .frame(minWidth: 200)
        }.frame(width: 600, height: 400)
    }
}

#Preview {
    TestView()
}

不带分隔线:

带分隔器:

如何添加宽度仅为填充侧边栏所需宽度的分隔线,而不影响其大小?

相关,如何在不影响侧边栏宽度的情况下左对齐侧边栏的内容?我在

.alignment
上使用
VStack
,但如果我尝试使其扩展以填充视图,它会更改视频的大小。

macos swiftui layout
1个回答
0
投票

如果您使用

NavigationSplitView
那么它可以开箱即用:

var body: some View {
    NavigationSplitView {
        SidebarView()
    } detail: {
        ContentView()
    }
}

否则,您可以将

Divider
显示为覆盖在
VStack
上。为了获得正确的间距,您可以使用同一文本的隐藏版本。比如:

struct SidebarView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Things")

            Spacer()

            Button("New Thing") {
                print("New Thing")
            }
        }
        .overlay(alignment: .top) {
            VStack {
                Text("Things").hidden()
                Divider()
            }
        }
        .padding()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.