swiftuibuttontext

SwiftUI - Getting text to center in a Button


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)
            )
        }
    }
}

Solution

  • 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