在不使用垫片的情况下将视图定位在底部 [英] Position view bottom without using a spacer
问题描述
如何在不使用垫片的情况下将视图放置在底部.我知道我可以实现在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] }
}
}
}
(示例屏幕截图的)使用示例
Usage example (of demo screenshot)
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()
}
}
这篇关于在不使用垫片的情况下将视图定位在底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!