You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI使用NavigationLink跳转页面后多余空白问题求助

解决SwiftUI NavigationLink跳转后多余空白的问题

问题根源

你遇到的多余空白是因为嵌套了多个NavigationView:MenuView已经通过NavigationView创建了导航容器,但CartView中又重复添加了NavigationView,导致跳转后出现双层导航结构,引发布局冲突和多余空白。.navigationBarHidden(true)无效也是因为嵌套结构导致设置无法生效。

解决方案

移除CartView中的NavigationView,直接在根视图上添加导航相关修饰符即可,因为父视图的NavigationView会自动管理子视图的导航状态。

修改后的CartView代码:

struct CartView: View {
    @EnvironmentObject var cartManager: CartManager
    var body: some View {
        VStack {
            ScrollView(.vertical, showsIndicators: false){
                if(cartManager.products.count > 0){
                    ForEach(cartManager.products, id: \.id){
                        product in
                        ProductRow(product: product)
                            .environmentObject(cartManager)
                    }
                    VStack {
                        HStack{
                            Text("Tax:")
                                .font(.title)
                            Spacer()
                            Text("$\(cartManager.tax, specifier: \"%.2f\")")
                                .bold()
                        }.padding()
                        HStack{
                            Text("Tip:")
                                .font(.title)
                            Spacer()
                            Text("$\(cartManager.tip, specifier: \"%.2f\")")
                                .bold()
                        }.padding()
                        HStack{
                            Text("Total:")
                                .font(.title)
                            Spacer()
                            Text("$\(cartManager.total, specifier: \"%.2f\")")
                                .bold()
                        }
                    }.padding()
                }else{
                    Spacer(minLength: 300)
                    Image(systemName: "takeoutbag.and.cup.and.straw.fill")
                        .font(.largeTitle)
                    Text("Your cart is empty!")
                        .font(.title2)
                    Text("Add things to your order to continue!")
                        .font(.title2)
                }
            }
        }
        .navigationTitle("Your Order")
        .navigationBarTitleDisplayMode(.automatic)
    }
}

补充说明

  • 调整后CartView会直接集成到MenuView的导航容器中,多余空白会自动消失。
  • 若你使用iOS 16及以上版本,推荐使用NavigationStack替代NavigationView,它的布局逻辑更清晰,也能避免这类嵌套问题。

内容的提问来源于stack exchange,提问作者Angellope12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:27:13