Home > Software engineering >  ZStack is laying out views differently when adding another view
ZStack is laying out views differently when adding another view

Time:02-28

I have this code:

ZStack {
    if let captionText = captionText {
        VStack {
            Spacer()
            Text(captionText)
                    .font(.small)
            }
    }
    
    user.username()
}

It looks like this (ignore the profile picture):

enter image description here

The 'admin' text position is very strange, it should be leading, equally as the username. When I add a HStack around the captionText, the username is... centered. This is totally unlogical for me:

enter image description here

and the code:

ZStack {
    if let captionText = captionText {
        VStack {
            Spacer()
            HStack {
                Text(captionText)
                    .font(.small)
                Spacer()
            }
        }
    }

    user.usernameFormattedText()
}

but the caption text is now correct. Any ideas why a ZStack changes the position of a View when a different View updates its position?

I fixed the problem by wrapping everything in HStacks and VStack with Spacers to make it work, but it is horrible. I am hoping I am just doing something wrong and the fix is easy.

CodePudding user response:

I believe you are just missing an alignment: .leading – and I don't understand why you use ZStack instead of VStack:

struct ContentView: View {
    
    var username = "[anonymous]"
    var captionText: String? = "Admin"
    
    var body: some View {
        HStack {
            Image(systemName: "person.circle")
                .font(.largeTitle)
            
            VStack(alignment: .leading) {
                Text(username)
                    .font(.headline).italic()
                
                if let captionText = captionText {
                    Text(captionText)
                        .font(.caption)
                }
            }
            .frame(maxWidth: .infinity, alignment: .center)
        }
        .padding()
        .frame(width: 300)
        .background(.gray)
    }
}

enter image description here

  • Related