user-interfaceswiftui

Horizontal text alignment in swiftUI


I'm trying to reproduce as on the mockup but I have the impression that the video quality text is not centred, here's the mockup and the rendering as well as my code

Figma

Rendering on the xcode canvas:

Canva xcode

I would like to center the text quality Video

var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Button(action: {}) {
                    Image(systemName: "chevron.left")
                        .foregroundColor(.white)
                        .padding()
                    
                }
                HStack {
                    Spacer()
                    Text("Qualité Vidéo")
                        .font(Fonts.Sora.bold.swiftUIFont(size: 19))
                        .foregroundColor(.white)
                        .multilineTextAlignment(.center)
                    Spacer()

                }

            }
            .padding(.horizontal)
            .padding(.bottom, 20)
            

Solution

  • The title is centered inside its own HStack, but then this is nested in another HStack together with the button. So this is why it is no longer centered in the final layout.

    To center the title with the least changes, you could change the outer HStack to a ZStack with (alignment: .leading). This way, the button and the title are combined as two layers:

    VStack(alignment: .leading, spacing: 16) {
        ZStack(alignment: .leading) { // 👈 HERE
            Button(action: {}) {
                // ...
            }
            HStack {
                // contains title as before
            }
        }
        // + padding as before
    }