【问题标题】:Right aligning a .bottomBar ToolbarItem in SwiftUI for iOS 14在 iOS 14 的 SwiftUI 中右对齐 .bottomBar ToolbarItem
【发布时间】:2020-12-06 01:21:35
【问题描述】:

我想在我的NavigationView 中的.toolbar.bottomBar 上添加一个“撰写”按钮。

添加一个Spacer() 只是几乎中心对齐项目:

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

这会产生以下内容:

不是我所期望的。更奇怪的是,它并没有完全居中对齐,它偏离了几个像素。

那我该怎么做:

  1. 右对齐?

  2. 居中对齐?

谢谢

【问题讨论】:

    标签: xcode swiftui ios14


    【解决方案1】:

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

    右对齐

    一种方法是使用两个.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")
            }
        }
    })
    

    居中

    要使项目居中,您可以使用.status 作为展示位置。

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

    【讨论】:

    • 完美解决方案
    【解决方案2】:

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

    使用 Xcode 12b3 测试

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

    注意:要使其居中删除带有空格的工具栏项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-14
      • 2020-10-27
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2020-12-07
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多