skip to Main Content

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)

The result of the above code
enter image description here

NOTE: It occupies the entire screen and not just the space occupied by its children

Expected Result
Expected Result

How can I achieve the above result? Thanks a lot for helping 🙂

2

Answers


  1. Chosen as BEST ANSWER

    For anyone looking for an answer, I ended up using maxWidth: .infinity. Basically, overlays and background 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 using

     ZStack {
            Text("Hello1").frame(maxWidth: .infinity, alignment: .leading)
            Text("Hello2").frame(maxWidth: .infinity, alignment: .trailing)
            
        }.frame(width: 300, height: nil).background(.red)
    

  2. It’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:

    struct ContentView: View {
        var body: some View {
            ZStack {
                HStack {
                    Text("Hello1")
                        .foregroundColor(.black)
                    Spacer()
                    Text("Hello2")
                        .foregroundColor(.black)
                }
            }
            .frame(width: 300)
            .background(.red)
        }
    }
    

    UPD: use .scaledToFit() for your ZStack

    struct ContentView: View {
        var body: some View {
            ZStack {
                Color.clear.overlay(alignment: .trailing) {
                    Text("Hello1")
                }
                Color.clear.overlay(alignment: .leading) {
                    Text("Hello2")
                }
            }
            .frame(width: 300)
            .background(.red)
            .scaledToFit()
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search