问题描述
如何在不使用间隔器的情况下将视图定位在底部.我知道我可以实现它在 VStack 中放置一个垫片和我的视图,但我不想使用垫片,因为我不希望我的视图占据所有垂直空间.使用 UIKit,我会将其放置在安全区域底部指南中.
How can I position a View at the bottom without using a spacer. I know I can achieve it placing a spacer and my view in inside a VStack but I don't want to use a spacer because I don't want my view to take up all the vertical space. With UIKit I would position it at safe area bottom guide.
推荐答案
尝试不同的方法我最终创建了自己的自定义容器,它有一些已知的限制,完全满足我的需求.希望对其他人有所帮助.
Experimenting with different approaches I finally end up with creating own custom container, which, having some known limitation, fulfils my needs completely. Hope it would be helpful for someone else.
演示:
优点:ContentView &PinnedView在布局上绝对独立,自动处理设备方向,内部内容实际上是无限的
Pros: ContentView & PinnedView are absolutely independent in layout on each other, automatically handle device orientation, and actually limitless in internal content
缺点:由于使用 GeometryReader
在顶级内容或固定视图中使用 .infinity
导致鸡-蛋"问题导致崩溃.
Cons: Due to used GeometryReader
using .infinity
at top-level content or pinned view result in crash due to "chicken-egg" problem.
容器代码:
struct ContainerWithPinnedBottomView<Content, Pinned>: View
where Content: View, Pinned: View {
private var content: () -> Content
private var bottomView: () -> Pinned
@inlinable public init(@ViewBuilder pinnedView: @escaping () -> Pinned,
@ViewBuilder content: @escaping () -> Content) {
self.content = content
self.bottomView = pinnedView
}
var body: some View {
ZStack(alignment: .bottom) {
Rectangle().fill(Color.clear) // !! Extends ZStack to full screen
GeometryReader { _ in
ZStack {
self.content()
}
}
self.bottomView()
.alignmentGuide(.bottom) { $0[.bottom] }
}
}
}
使用示例(演示截图)
struct TestBottomView: View {
var body: some View {
ContainerWithPinnedBottomView(pinnedView: {
HStack {
Spacer()
Text("Always Pinned to Bottom")
.padding()
// .frame(width: .infinity) // !! LIMITATION - don't use, cycling crash
Spacer()
}
.background(Color.blue)
}) {
NavigationView {
List (0 ..< 100, id: .self) { i in
NavigationLink(destination: Text("Other")) {
Text("Row (i)")
}
}
.navigationBarTitle("TitleBar")
}
}
}
}
struct TestBottomView_Previews: PreviewProvider {
static var previews: some View {
TestBottomView()
}
}
这篇关于不使用垫片定位视图底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!