gpt4 book ai didi

在 ZStack 中时 SwiftUI 不居中

转载 作者:行者123 更新时间:2023-12-05 06:04:44 25 4
gpt4 key购买 nike

我正在尝试将一个 View 放在一起,该 View 由顶部标题 View 、底部内容 View 和位于顶部的 View 组成,该 View 以分割两个 View 的线为中心。我发现我需要 ZStack 中的对齐指南来定位中间 View ,但我无法让下方内容 View 中的项目无间隙地居中。

这段代码:

extension VerticalAlignment {
struct ButtonMid: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.bottom]
}
}
static let buttonMid = VerticalAlignment(ButtonMid.self)
}

struct ContentView: View {
var body: some View {
VStack {
ZStack(alignment: Alignment(horizontal: .center, vertical: .buttonMid)) {
HeaderView()
.frame(maxWidth: .infinity, minHeight: 200, idealHeight: 200, maxHeight: 200, alignment: .topLeading)

// BodyView()
// .alignmentGuide(.buttonMid, computeValue: { dimension in
// return dimension[VerticalAlignment.top]
// })

Color.red
.frame(width: 380, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.alignmentGuide(.buttonMid, computeValue: { dimension in
return dimension[VerticalAlignment.center]
})
}

BodyView()
}
.edgesIgnoringSafeArea(.top)
}
}

struct HeaderView: View {
var body: some View {
Color.green
}
}

struct BodyView: View {
var body: some View {
VStack {
Spacer()
HStack {
Spacer()
BodyContent()
Spacer()
}
Spacer()
}
.background(Color.blue)
}
}

struct BodyContent: View {
var body: some View {
VStack {
Text("Line 1")
Text("Line 2")
Text("Line 3")
}
}
}

给你这个:

enter image description here

按照我想要的方式将较低的内容居中,但是它在上下 View 之间留下了间隙。如果我取消注释 ZStack 中的 BodyView 代码并在 VStack 中将其注释掉,如下所示:

struct ContentView: View {
var body: some View {
VStack {
ZStack(alignment: Alignment(horizontal: .center, vertical: .buttonMid)) {
HeaderView()
.frame(maxWidth: .infinity, minHeight: 200, idealHeight: 200, maxHeight: 200, alignment: .topLeading)

BodyView()
.alignmentGuide(.buttonMid, computeValue: { dimension in
return dimension[VerticalAlignment.top]
})

Color.red
.frame(width: 380, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.alignmentGuide(.buttonMid, computeValue: { dimension in
return dimension[VerticalAlignment.center]
})
}

// BodyView()
}
.edgesIgnoringSafeArea(.top)
}
}

给你:

enter image description here

使内容不居中。我怎样才能让它居中?我尝试将其放入 GeometryReader 中,结果相同。

最佳答案

您不需要自定义 VerticalAlignment。相反,您可以将中间 View 作为叠加层并将其与底部 View 的顶部边框对齐:

struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
HeaderView()
.frame(height: 200)
BodyView()
.overlay(
Color.red
.frame(width: 380, height: 50)
.alignmentGuide(.top) { $0[VerticalAlignment.center] },
alignment: .top
)
}
.edgesIgnoringSafeArea(.top)
}
}

关于在 ZStack 中时 SwiftUI 不居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66231429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com