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

Time:12-20

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.

CodePudding user response:

Try the below code:

       HStack {
                  Text("1")
                      .multilineTextAlignment(.leading)
                  Text("2")
                      .multilineTextAlignment(.center)
                      .frame(minWidth: 0, maxWidth: .infinity)
              }

CodePudding user response:

Add a Spacer to your HStack after each Text. This will give you the first Text at the left and the second starting in the middle

HStack {
    Text("1")
        .multilineTextAlignment(.leading)
        .frame(alignment: .leading)
        .padding(.leading)

    Spacer()

    Text("2")
        .multilineTextAlignment(.center)
        .frame(alignment: .center)
        .padding(.trailing)

    Spacer()
}

CodePudding user response:

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()
  • Related