swiftUI 中如何将 view 添加到 navigationbar 中?

我在用 swiftUI 写一个列表界面,代码如下

struct ListView: View {
    @State private var showMenu = false
    @State private var persons = ["person 1", "person 2", "person 3"] // 用于演示的假数据

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(persons, id: \.self) { person in
                        Text(person)
                            .listRowSeparator(.hidden)
                            .padding()
                            .onTapGesture {
                                //  点击进入详情
                            }
                    }
                }
                .background(Color.white)
                .statusBar(hidden: false)
            }
            .navigationBarItems(trailing:
                Button(action: {
                    showMenu.toggle()
                }) {
                    Image(systemName: "line.horizontal.3")
                        .font(.system(size: 22))
                        .foregroundColor(.black)
                }
            )
            .background(Color.white)
            .sheet(isPresented: $showMenu) {
                MenuView()
            }
            .navigationBarTitle("", displayMode: .inline) // 隐藏导航栏标题
            .navigationBarColor(backgroundColor: .white, tintColor: .black) // 设置导航栏颜色
            .navigationBarBackButtonHidden(true) // 隐藏返回按钮
            .overlay(
                TitleBlock()
                    .frame(width: 180, height: 40)
            )
        }
    }
}

// 分类的标题
struct TitleBlock: View {
    var body: some View {
        HStack(spacing: 0) {
            Text("Age")
                .frame(maxWidth: .infinity)
            Text("Sex")
                .frame(maxWidth: .infinity)
            Text("Grade")
                .frame(maxWidth: .infinity)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color(hex: "f1f1f1"))
        .cornerRadius(4)
    }
}

通过 overlay 将 TitleBlock 这个 view 添加到顶部导航的 bar 上,但现在出现的问题是,这个 TitleBlock view 不显示在 navigationBar 上,而是水平居中,垂直居中的显示在整个界面的中间。请问正确的在 navigationBar 上添加这个 view 的方式是什么呢?

我尝试通过绝对位置来实现,但也一样的问题。

阅读 1.1k
1 个回答

试一试对齐方式 alignment

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏