防止列表中的最后一行被ZStack中的其他视图覆盖

时间:2020-08-23 15:37:16

标签: swift swiftui swiftui-list swiftui-zstack

我有一个List被半透明视图部分覆盖(我们称其为覆盖)。我的问题是,对于长列表,由于覆盖了它们,因此无法访问最后一行。

我正在使用ZStack来布局最终视图。我曾考虑过要在最后一行添加填充,这可能会使列表内容变大,因此它可以完全滚动出覆盖层,但我不知道该怎么做,甚至不知道如果使用ZStack是处理列表的正确方法。

what I get

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,所以我对如何搜索正确的术语还有些迷茫。

1 个答案:

答案 0 :(得分:1)

可能的解决方案是计算覆盖区域的高度,并将具有该高度的透明视图添加到列表的底部。

这里是使用视图首选项的方法演示。经过Xcode 12 / iOS 14的测试

demo

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()
    }
}