0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I want the username to be centered horizontally and the captionText to be at the bottom, that's why I used a ZStack
you want the username centered, and the captiontext leading aligned to that? – I updated my answer.
or do you want the username centered VERTICALLY ?
I just went with the VStack as you mentioned, it doesn't look 100% the way I wanted, but it's fine. The ZStack is doing some weird stuff

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.