SwiftUI Widget - ZStack

The function of ZStack is to layer the widget on top of each other. Widget stacked on top cover the visible portion of the widget stacked below and those widgets can be aligned in both axes.

How to layer a text on a shape

Let’s look at a code snippet

1
2
3
4
5
6
7
8
9
10
11
12
struct ZStackView: View {
var body: some View {
ZStack() {
Circle()
.frame(width: 100, height: 100)
.foregroundColor(.green)

Text("Hello")
.foregroundColor(.white)
}
}
}

In this example, we layer a Text - ‘Hello’ on a Circle. Becuase the default alignment is center, you can see the Text in center of the Circle.

How to align those widgets in ZStack

You can use the ‘alignment’ property to do it. such as:

1
2
3
4
5
6
7
8
9
10
11
12
struct ZStackView: View {
var body: some View {
ZStack(alignment: .bottomLeading) {
Circle()
.frame(width: 100, height: 100)
.foregroundColor(.green)

Text("Hello")
.foregroundColor(.white)
}
}
}

This will align both widgets to the lower-left corner. We didn’t set the frame for the entire ZStack, ZStack will use the frame of the circle, So we can only see that text is aligned.

To see the both widgets(Circle and Text) are aligned. We change the code as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct ZStackView: View {
var body: some View {
ZStack(alignment: .bottomLeading) {
Circle()
.frame(width: 100, height: 100)
.foregroundColor(.green)

Text("Hello")
.foregroundColor(.white)
}
.frame(width: 300, height: 300, alignment: .bottomLeading)
.background(Color.gray)
}
}

Now you can see the both widgets are aligned to bottom left corner.

About more detail of ZStack widget, you can see the Official Documentation

本文标题:SwiftUI Widget - ZStack

文章作者:Morning Star

发布时间:2022年01月23日 - 12:01

最后更新:2022年01月23日 - 14:01

原始链接:https://www.mls-tech.info/app/swift/swiftui-widget-zstack/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。