I want to use alignmentGuide to align center a Text view in ZStack to implement view as bellow, blue block is align traling, Text "abc" and "123" is align center of view.
My code is as bellow:
extension HorizontalAlignment {
private enum MyHorizontalAlignment : AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
return d[HorizontalAlignment.center]
}
}
static let myHorizontalAlignment = HorizontalAlignment(MyHorizontalAlignment.self)
}
extension Alignment {
static let myAlignment = Alignment(horizontal: .myHorizontalAlignment, vertical: .center)
}
struct ContentView: View {
var body: some View {
VStack() {
VStack() {
ZStack(alignment: .myAlignment) {
Rectangle()
.foregroundColor(.gray)
.frame(height: 100)
.padding(.horizontal, 20)
VStack() {
Rectangle()
.frame(width: 100, height: 30)
.foregroundColor(.blue)
//Text("12345678")
.alignmentGuide(.myHorizontalAlignment) { d in
d.width/2.0 - (160-100)/2.0
}
HStack() {
Text("123")
Text("456")
}
}
}
}
.frame(width: 200, height: 200)
.background(Color.gray.opacity(0.4))
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.white)
}
}
But the "abc" and "123" in not center.
I know that it can use Spacer and offset to implement it. But how to use alignmentGuide to implement it?



While this may not be the exact answer using custom alignmentGuide, I believe it's a much more straightforward, simpler and concise approach. Instead, I utilized the built-in frame alignments, which allow you to adjust the frame sizes, paddings, and other constants of elements, ensuring consistent alignment.
Image with original frame sizes and padding.
Image with different frame sizes and padding.