RealTechyGod
RealTechyGod

Reputation: 131

Text is centering in view instead of trailing the view

Why is the "..." not trailing? it should be on the right of the screen always not the center.

ZStack {
    HStack {
        Text("Good morning")
            .padding(.leading, 20.0)
            .font(.subheadline)
            .background(Color.yellow)
        Spacer()
    }
    HStack {
        Text("...")
            .foregroundColor(.blue)
            .frame(alignment: .trailing)
            .font(.title3)
            .multilineTextAlignment(.trailing)
    }
}

Upvotes: 1

Views: 127

Answers (2)

RealTechyGod
RealTechyGod

Reputation: 131

Ok so the answer is to remove the ZStack and add the spacer in the middle... Like This!

HStack {
    Text("Good morning")
        .padding(.leading, 20.0)
        .font(.subheadline)
        .background(Color.yellow)
    Spacer()
    
    Text("...")
        .foregroundColor(.blue)
        .frame(alignment: .trailing)
        .font(.title3)
        .multilineTextAlignment(.trailing)
}

This article is what helped (after input from @pawello2222)

Spacers are essentially </span> once you think of it like that it becomes logical.

Upvotes: 1

pawello2222
pawello2222

Reputation: 54486

You need another Spacer:

ZStack {
    HStack {
        Text("Good morning")
            .padding(.leading, 20.0)
            .font(.subheadline)
            .background(Color.yellow)
        Spacer()
    }
    HStack {
        Spacer() // <- add here
        Text("...")
            .foregroundColor(.blue)
            // .frame(alignment: .trailing) // can be removed
            .multilineTextAlignment(.trailing)
    }
}

Tested with Xcode 11.6, iOS 13.6.


You can read more about .frame(alignment: .trailing) here:

Upvotes: 1

Related Questions