Search code examples
swiftswiftuialignmenthstack

How to align text to the left and in the middle of a view


I have two Texts: Text("1") and Text("2") in an HStack. I want Text("1") to be in the leftmost part of ContentView and Text("2") to be in the exact horizontal center of ContentView.

Here's my code:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        HStack {
            Text("1")
                .multilineTextAlignment(.leading)
                .frame(
                    alignment: .leading
                )
            Text("2")
                .multilineTextAlignment(.center)
                .frame(
                    alignment: .center
                )
        }
        .frame(width: .infinity)
        
    }
}

When I run this though, both Text("1") and Text("2") remain in the general horizontal center of ContentView. Not sure what I'm doing wrong.


Solution

  • Here's another way you can do this by using ZStack. Second text will always be in exact centre.

    ZStack {
        HStack {
            Text("1")
            Spacer()
        }
                                
        HStack {
            Spacer()
            Text("2")
            Spacer()
        }
    }
    .padding()