How to adjust navigationBarTitle and Label Text alignment in SwiftUI

Viewed 138

I just learned swiftUI and I got little trouble. I want to make navigationBarTitle and title headline alignment like this:

Image 1: I want to make my view like this

I have tried to make like below but it does not work:

struct HeaderView: View {
var body: some View {
    NavigationView {
        VStack {
            Image("kante_training_champions_league")
                .resizable()
                .scaledToFill()
                .frame(width: 370, height: 150)
                .cornerRadius(10.0)
            Text("KANTE: NEW PLAYERS DON’T SEEM NEW")
                .font(.title)
                .fontWeight(.bold)
                .multilineTextAlignment(.leading)
                .frame(width: 370)
            Spacer()
        }
        .navigationBarTitle("Chelsea FC")
    }
  }
}

From my code above, I got a view like this:

Image 2: I got a view like this from my code above

Could someone help me how to get a view like I want

3 Answers

Try leading alignment

var body: some View {
    NavigationView {
        VStack(alignment: .leading) {     // << here !!

        // ... no changes in image

        Text("KANTE: NEW PLAYERS DON’T SEEM NEW")
            .font(.title)
            .fontWeight(.bold)
            .padding(.leading)                    // << here !!
            .multilineTextAlignment(.leading)

}

You should add alignment to StackView. You can change alignment to .leading, .trailing or .center. It is centered by default thats why you are having the label in center.

var body: some View {
  NavigationView {
    VStack(alignment: .leading) {    
    // Your Code
    }
  }
}

Remove .frame(width: 370) and use .frame(maxWidth: .infinity) so that the text takes the whole width of its parent.

        VStack {
            Image("kante_training_champions_league")
                .resizable()
                .scaledToFill()
                .frame(width: 370, height: 150)
                .cornerRadius(10.0)
            Text("KANTE: NEW PLAYERS DON’T SEEM NEW")
                .font(.title)
                .fontWeight(.bold)
                .multilineTextAlignment(.leading)
                .frame(maxWidth: .infinity)
            Spacer()
        }
Related