在iOS 14的SwiftUI中右对齐.bottomBar ToolbarItem

问题描述

我想在.bottomBar的{​​{1}}的{​​{1}}的{​​{1}}上添加一个“ compose”按钮。

添加一个.toolbar只需几乎中心即可对齐该项目:

NavigationView

这将产生以下结果:

Center aligned toolbar item

不是我所期望的。甚至更奇怪的是,它没有完全居中对齐,只有几个像素的距离。

那我该怎么办

  1. 右对齐?

  2. 居中对齐?

谢谢

解决方法

我遇到了同样的问题,这是我发现的(Xcode 12.0 Beta 6)

右对齐

Example of Right Aligned

一种方法是使用两个.bottomBar项目。

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

更清洁的方法是将ToolbarItemGroupSpacer()一起使用。

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

居中

Example of Centered

要使某个项目居中,可以使用.status作为放置位置。

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

每个ToolbarItem都必须包含单个视图,因此只需将Spacer移到单独的工具栏项中

通过Xcode 12b3测试

demo

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

注意:将其居中删除带有分隔符的工具栏项