-2

enter image description here

I am trying to get the text in the above Button to centre. The format is controlled by a style sheet Struct - StatusBarEndText. Any ideas?

ToolbarItem(placement: .topBarTrailing) {
    Button("ABCDEF") {
        start.toggle()
    }
    .statusBarEndTextStyle()
}
struct StatusBarEndText: ViewModifier {
    func body(content: Content) -> some View {
        content
            .frame(width: 72, height: 28, alignment: .center)
            .multilineTextAlignment(.center)
            .font(.body)
            .lineLimit(1)
            .foregroundColor(.white)
            .background(start ? .gray .opacity(0.5) : .green)
            .cornerRadius(8)
            .overlay(
                RoundedRectangle(cornerRadius: 8)
                    .stroke(.black, lineWidth: 1)
            )
        }
    }
}

1 Answer 1

2

Try applying the modifier to the label of the button, instead of to the surrounding button:

ToolbarItem(placement: .topBarTrailing) {
    Button {
        start.toggle()
    } label: {
        Text("ABCDEF")
            .statusBarEndTextStyle()
    }
}

You might also like to consider letting the text find its own size, instead of setting a fixed width and height. To do this, replace the .frame modifier with .fixedSize() and then add some padding, as required:

content
    // .frame(width: 72, height: 28, alignment: .center)
    .fixedSize()
    .padding(4)
    // ... + other modifers, as before

Screenshot

Sign up to request clarification or add additional context in comments.

1 Comment

YES - that resolves the issue - now centered. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.