提问人:dhaval123 提问时间:3/8/2023 更新时间:3/14/2023 访问量:321
披露组标题作为 SwiftUI 的固定标头
disclosure group title as pinned header for swiftui
问:
我有一个很大的披露小组,它比整个屏幕都大。它基本上是大量的文本。
如何在顶部添加固定标题,我会向下滚动吗?
我需要这个,因为我希望用户知道它目前正在阅读哪个披露组。
部分已经这样做了,但我想使用披露组,因为它们更容易绑定,以及展开/折叠。
该部分有一个教程,但我想要披露组:https://swiftontap.com/pinnedscrollableviews/sectionheaders
这可能就是披露组吗?
DisclosureGroup("First description") {
Text("big amount of text")
}
答:
1赞
Hongtron
3/8/2023
#1
使用 DisclosureGroup 似乎很困难,但我可以使用如下所示的自定义视图非常简单地复制复制相似的类型行为。这有点初级,但希望能给你一些想法和一些实用的东西。您可以在 CustomDisclosure HStack 中复制 DisclosureGroup 外观并展开 V 形。需要注意的主要问题是 ZStack 试图占用它提供的所有空间,因此有时如果有可用空间,折叠的行似乎会保持其扩展大小。你可以进一步努力的事情。
我更新了自定义 DiscloseView,因此它现在将展开的视图作为闭包,与 DisclosureGroup、VStack 等相同,因此您可以根据需要自定义扩展视图。
import SwiftUI
struct CustomDisclosure<ExpandedView: View>: View {
var title: String
var contentView: () -> ExpandedView
@State var isExpanded: Bool = false
init(_ title: String , @ViewBuilder _ content: @escaping () -> ExpandedView) {
self.title = title
self.contentView = content
}
var body: some View {
Section {
if isExpanded {
contentView()
}
} header: {
HStack {
Text(title)
.foregroundColor(.blue)
Spacer()
Image(systemName: "chevron.right")
}.onTapGesture {
isExpanded.toggle()
}
.background(.white)
.padding(.bottom , 12)
}
}
}
struct ContentView: View {
var body: some View {
ScrollView {
LazyVStack(pinnedViews: .sectionHeaders) {
ForEach(1..<20) { i in
CustomDisclosure("Test \(i)") {
Text(bigText)
}
}
}
}
.padding()
}
var bigText: String = "Big Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \nBig Amount of text \n"
}
评论
0赞
dhaval123
3/8/2023
好主意。问题是我不只使用文本,我使用图像、列表、其他视图等
0赞
Hongtron
3/8/2023
您可以将 var text: String 更改为视图而不仅仅是字符串?你知道怎么做吗,或者我可以更新这个例子。
0赞
dhaval123
3/8/2023
我是 swift 的新手,如果您能向我展示,我将不胜感激
0赞
Hongtron
3/8/2023
我已经更新了答案,因此 CustomDisclosure 现在将视图作为闭包,与 DisclosureGroup、VStack 等相同,因此您可以将其与任何视图内容相同。需要注意的一点是,通过使用 ZStack,标题实际上位于滚动视图的顶部,因此我添加了标题的隐藏版本作为该视图的顶部,以将滚动视图推到标题下方。
0赞
dhaval123
3/9/2023
但这在经过时仍然没有像在部分中那样显示标题
评论