Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right aligning a .bottomBar ToolbarItem in SwiftUI for iOS 14

I'd like to add a "compose" button onto the .bottomBar of a .toolbar in my NavigationView.

Adding a Spacer() simply almost center aligns the item:

struct HomeView: View {
    var body: some View {
        NavigationView {
            Text("Hello, World!")
                .navigationTitle("Hello, World!")
                .toolbar {
                    ToolbarItem(placement: .bottomBar) {
                        HStack {
                            Spacer()
                            Button(action: { print("Pressed") }) {
                                Image(systemName: "plus.circle.fill")
                                    .imageScale(.large)
                                    .font(.title)
                            }
                        }
                    }
                }
        }
    }
}

This produces the following:

Center aligned toolbar item

Not what I would have expected. What's even stranger is that that's not exactly center aligned, it's off by a few pixels.

So how do I:

  1. Right align?

  2. Center align?

Thanks

like image 460
Thor Correia Avatar asked Aug 16 '20 20:08

Thor Correia


2 Answers

I had this same problem, here's what I found (Xcode 12.0 Beta 6)

Right Aligned

Example of Right Aligned

One way to do this is to use two .bottomBar items.

.toolbar(content: {
    ToolbarItem(placement: .bottomBar) {
        Spacer()
    }
    ToolbarItem(placement: .bottomBar) {
        Button(action: {}) {
            Text("Add List")
        }
    }
})

A bit cleaner is to use a ToolbarItemGroup with a Spacer().

.toolbar(content: {
    ToolbarItemGroup(placement: .bottomBar) {
        Spacer()
        Button(action: {}) {
            Text("Add List")
        }
    }
})

Centered

Example of Centered

To center an item you can use .status as the placement.

.toolbar(content: {
    ToolbarItem(placement: .status) {
        Button(action: {}) {
            Text("Add List")
        }
    }
})
like image 76
JT Bergman Avatar answered Nov 14 '22 08:11

JT Bergman


Every ToolbarItem have to include single view, so just move Spacer into separated toolbar item

Tested with Xcode 12b3

demo

    .toolbar {
        ToolbarItem(placement: .bottomBar) {
            Spacer()
        }
        ToolbarItem(placement: .bottomBar) {
            Button(action: { print("Pressed") }) {
                Image(systemName: "plus.circle.fill")
                    .imageScale(.large)
                    .font(.title)
            }
        }
    }

Note: to have it centered remove toolbar item with spacer

like image 34
Asperi Avatar answered Nov 14 '22 10:11

Asperi