SwiftUI中的边栏列表样式不起作用

uz75evzq  于 2023-10-15  发布在  Swift
关注(0)|答案(1)|浏览(127)

我在SwiftUI中的一个视图中创建了一个列表,并将其样式设置为.sideBar,但它没有被应用。没有扩展按钮。会是什么问题呢?有什么办法吗?(我的最低部署是iOS 16.2)

import SwiftUI

struct ListTestView: View {
    
    var body: some View {
        List {
            Section(content: {
                Text("...")
                Text("...")
                Text("...")
                Text("...")
            }, header: {
                Text("Hedaer")
                    .textCase(nil)
            })
        }
        .listStyle(.sidebar)
    }
    
}

#Preview {
    ListTestView()
}

aij0ehis

aij0ehis1#

.sidebar列表样式只是在标题中添加一个V形符号。允许用户折叠/展开部分。

iOS 17+解决方案

Apple
在macOS和iOS上,侧边栏列表样式在节标题中显示公开指示符,允许用户折叠和展开节。
似乎没有记录的是,您必须使用在其初始化器中包含isExpandedSection

struct ListTestView: View {
    @State var showingFirstSection = true
    
    var body: some View {
        List {
            Section(
                isExpanded: $showingFirstSection,
                content: {
                    Text("...")
                }, header: {
                    Text("Header")
                }
            )
        }
        .listStyle(.sidebar)
    }
}

当您使用isExpanded创建Section时,只要列表样式为.sidebar,就会出现V形符号

iOS 16-解决方案

我尝试了所有其他的Section初始化器,没有一个提供.sidebar列表样式的chevron。由于SwiftUI没有提供预期的功能,我建议使用自定义的Section实现。这个CollapsibleSection只使用基本的Section初始化器,并公开了一个showingContent可绑定对象来模拟isExpanded部分的行为。

struct CollapsibleSection<C, H>: View where C: View, H: View {
    @Binding var showingContent: Bool
    var content: C
    var header: H
    
    @inlinable
    init(showingContent: Binding<Bool>, @ViewBuilder content: () -> C, @ViewBuilder header: () -> H) {
        self._showingContent = showingContent
        self.content = content()
        self.header = header()
    }
    
    var body: some View {
        Section(
            content: {
                if showingContent {
                    content
                }
            },
            header: {
                HStack {
                    header
                    Spacer()
                    Image(systemName: "chevron.down")
                        .rotationEffect(showingContent ? .zero : .degrees(-90))
                        .onTapGesture {
                            withAnimation {
                                showingContent.toggle()
                            }
                        }
                }
            }
        )
    }
}

与iOS 17+解决方案相同

CollapsibleSection(
    showingContent: $showingFirstSection,
    content: {
        Text("...")
        Text("...")
        Text("...")
    },
    header: {
        Text("Header")
    }
)

相关问题