gpt4 book ai didi

ios - View 以 super View 为中心,在 SwiftUI 中 View 位于其顶部

转载 作者:行者123 更新时间:2023-12-01 17:46:04 25 4
gpt4 key购买 nike

我正在尝试在 UIKit 中实现一些非常容易的事情——一个 View 始终位于中心(图像),第二个 View (文本)位于其顶部,两个 View 之间有一些间距。我尝试了许多不同的方法(主要使用 alignmentGuide,但没有任何效果)。
代码:

ZStack {
Rectangle()
.foregroundColor(Color.red)

VStack {
Text("Test")
.padding([.bottom], 20) // I want to define spacing between two views

Image(systemName: "circle")
.resizable()
.alignmentGuide(VerticalAlignment.center, computeValue: { value in
value[VerticalAlignment.center] + value.height
})
.frame(width: 20, height: 20)
}
}
.frame(width: 100, height: 100)
结果:
enter image description here
如您所见,图像不是完全居中的,它实际上取决于 Text 的填充值。 .有没有办法强制垂直和水平对齐在 super View 和布局第二个 View 中居中而不影响居中 View ?

最佳答案

我认为这样做的“正确”方法是定义自定义对齐方式:

extension VerticalAlignment {
static var custom: VerticalAlignment {
struct CustomAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
context[VerticalAlignment.center]
}
}
return .init(CustomAlignment.self)
}
}
然后,告诉您的 ZStack使用 custom对齐,并使用 alignmentGuide显式设置 custom在你的圈子上对齐:
PlaygroundPage.current.setLiveView(
ZStack(alignment: .init(horizontal: .center, vertical: .custom)) {
Color.white

Rectangle()
.fill(Color.red)
.frame(width: 100, height: 100)

VStack {
Text("Test")
Circle()
.stroke(Color.white)
.frame(width: 20, height: 20)
.alignmentGuide(.custom, computeValue: { $0.height / 2 })
}
}
.frame(width: 300, height: 300)
)
结果:
enter image description here

关于ios - View 以 super View 为中心,在 SwiftUI 中 View 位于其顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63303653/

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