我认为做到这一点的“正确”方法是定义自定义对齐方式:
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)
)
结果:
,
您可以通过将Image
移到ZStack
来居中。然后将.alignmentGuide
应用于Text
:
struct ContentView: View {
var body: some View {
ZStack {
Rectangle()
.foregroundColor(Color.red)
Text("Test")
.alignmentGuide(VerticalAlignment.center) { $0[.bottom] + $0.height }
Image(systemName: "circle")
.resizable()
.frame(width: 20,height: 20)
}
.frame(width: 100,height: 100)
}
}
请注意,在您明确指定Image
的宽度/高度时:
Image(systemName: "circle")
.resizable()
.frame(width: 20,height: 20)
您也可以明确指定.alignmentGuide
:
.alignmentGuide(VerticalAlignment.center) { $0[.bottom] + 50 }
,
在这里可以使用自动占用空间功能来替代
通过Xcode 12 / iOS 14测试
struct ContentView: View {
var body: some View {
ZStack {
Rectangle()
.foregroundColor(Color.red)
VStack(spacing: 0) {
Color.clear
.overlay(
Text("Test").padding([.bottom],10),alignment: .bottom)
Image(systemName: "circle")
.resizable()
.frame(width: 20,height: 20)
Color.clear
}
}
.frame(width: 100,height: 100)
}
}
注意:在我将Spacer()
用于此目的之前,但在Swift 2.0中,似乎spacer始终只是一个spacer,即。什么都没有附上-可能是错误。
本文链接:https://www.f2er.com/1786426.html