I am trying to custom align views in a Z-Stack using overlays. It works fine till my Z-stack has an absolute height dimension, it breaks when I set the height of my Z-stack to nil
only to occupy space that is used by its children. Here is the code I am using
ZStack {
Color.clear.overlay(alignment: .trailing) {
Text("Hello1")
}
Color.clear.overlay(alignment: .leading) {
Text("Hello2")
}
}.frame(width: 300, height: nil).background(.red)
NOTE: It occupies the entire screen and not just the space occupied by its children
How can I achieve the above result? Thanks a lot for helping 🙂
2
Answers
For anyone looking for an answer, I ended up using
maxWidth: .infinity
. Basically,overlays
andbackground
don't have a say in the parent view's height/width. Hence, they cant be used if you want your parent view to occupy the size of its children. Here is the code I ended up usingIt’s not so clear why you use Color with Text overlay, but we can achieve result as you expect on the second image like that:
UPD: use
.scaledToFit()
for yourZStack