trapper
trapper

Reputation: 12003

SwiftUI How to center Text in a Form?

.multilineTextAlignment(.center) seems to have no effect when the Text is inside Form, how can I center this item?

Form {
    Text("I am left aligned")
    Text("Why won't I center?").multilineTextAlignment(.center)
}

Upvotes: 27

Views: 16270

Answers (5)

trapper
trapper

Reputation: 12003

This works.

Form {
    Text("I am left aligned")
    Text("I am centered!")
    .frame(maxWidth: .infinity, alignment: .center)
}

Upvotes: 35

Edward Brey
Edward Brey

Reputation: 41738

Use frame to expand the text's frame to the full width and multilineTextAlignment to cause text (including wrapped text) to be centered.

Form {
    Text("Centered text, even if wraps")
        .frame(maxWidth: .infinity)
        .multilineTextAlignment(.center)
}

Upvotes: 15

oskarko
oskarko

Reputation: 4178

If you have two elements (i.e. 2 Texts) inside a HStack and need to put the second Text in the center, a little trick is to insert a third hidden element like the first one.

HStack(alignment: .center) {
            Button(action: {
                print("later...")
            }) {
                Text("Later")
            }
            .font(font)
            Text("Centered Text")
                .foregroundColor(SwiftUI.Color(.white))
                .frame(minWidth: 0,
                       maxWidth: .infinity,
                       minHeight: 0,
                       maxHeight: .infinity,
                       alignment: .center)
            Button(action: {
                print("later...")
            }) {
                Text("Later")
            }
            .hidden()
        }

Upvotes: 1

Peter Schorn
Peter Schorn

Reputation: 997

In case you need to center several items in the center of forms, here's a struct that accepts an object conforming to view for you to display:

struct CenterInForm<V: View>: View {

    var content: V

    init(_ content: V) { self.content = content }

    var body: some View {
        HStack {
            Spacer()
            content
            Spacer()
        }
    }
}

Usage:

CenterInForm(Text("TOTAL: $100"))
CenterInForm(Button("Confirm order") { print("placing order") })

Upvotes: 4

josefdolezal
josefdolezal

Reputation: 493

You can wrap your text into HStack:

Form {
    Text("I am left aligned")
    HStack {
        Spacer()
        Text("I am centered!")
        Spacer()
    }
}

Upvotes: 17

Related Questions