如何解决防止列表中的最后一行被ZStack中的其他视图覆盖
我有一个List
被半透明视图部分覆盖(我们称其为覆盖)。我的问题是,对于长列表,由于覆盖了它们,因此无法访问最后一行。
我正在使用ZStack
来布局最终视图。我曾考虑过要在最后一行添加填充,这可能会使列表内容变大,因此它可以完全滚动出覆盖层,但我不知道该怎么做,甚至不知道如果使用ZStack
是处理列表的正确方法。
import SwiftUI
struct ListWithBottomOverlay: View {
var body: some View {
GeometryReader { proxy in
ZStack {
List {
ForEach(1..<20) { number in
Text("\(number)")
}
}
VStack {
Spacer().frame(maxHeight: .infinity)
VStack {
HStack {
Button(action: {},label: { Text("Hello") })
.frame(minHeight: 100)
}
HStack {
Button(action: {},label: { Text("World!") })
.frame(minHeight: 100)
}
}
.frame(maxWidth: .infinity)
.background(Color(.yellow).opacity(0.8))
}
}
}
}
}
struct ListWithBottomOverlay_Previews: PreviewProvider {
static var previews: some View {
ListWithBottomOverlay()
}
}
如果这是一个重复的问题,我深表歉意,我才刚刚开始学习SwiftUI,所以我对如何搜索正确的术语还有些迷茫。
解决方法
可能的解决方案是计算覆盖区域的高度,并将具有该高度的透明视图添加到列表的底部。
这里是使用视图首选项的方法演示。经过Xcode 12 / iOS 14的测试
struct ListWithBottomOverlay: View {
@State private var height = CGFloat.zero
var body: some View {
GeometryReader { proxy in
ZStack {
List {
ForEach(1..<20) { number in
Text("\(number)")
}
Color.clear.frame(height: height) // injected empty space
}
VStack {
Spacer().frame(maxHeight: .infinity)
VStack {
HStack {
Button(action: {},label: { Text("Hello") })
.frame(minHeight: 100)
}
HStack {
Button(action: {},label: { Text("World!") })
.frame(minHeight: 100)
}
}
.frame(maxWidth: .infinity)
.background(GeometryReader {
// use color filled area in background to read covered frame
Color(.yellow).opacity(0.8)
.edgesIgnoringSafeArea(.bottom)
.preference(key: ViewHeightKey.self,value: $0.frame(in: .local).size.height)
})
}
}
.onPreferenceChange(ViewHeightKey.self) {
// view preferences transferred in one rendering cycle and
// give possibility to update state
self.height = $0
}
}
}
}
struct ViewHeightKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value,nextValue: () -> Value) {
value += nextValue()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。