'ToolbarItem(placement: .navigationBarTrailing) positions icon to trailing edge of parent view

enter image description here

I have installed a button in the navigation bar. I have positioned it on the trailing edge. I am using an image to populate the button's label. The label appears right alignment. How can I centre this?

ToolbarItem(placement: .navigationBarTrailing) {
    Button {
        // action
    } label: {
        Image(systemName: "keyboard")
    }
    .border(.red, width: 1)
}


Solution 1:[1]

This is how default button style works. It can be turned off by using plain style and then you can design it as you want (in-place or wrap into own style)

Tested with Xcode 13.3 / iOS 15.4

demo

ToolbarItem(placement: .navigationBarTrailing) {
    Button {
        // action
    } label: {
        Image(systemName: "keyboard")
            .foregroundColor(.blue).padding(4)     // << here !!
    }
    .buttonStyle(PlainButtonStyle()) // turn off design, only behavior 
    .border(.red, width: 1)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asperi