SwiftUi Navigation Bar Button 进入第三个View(Controller)后消失

SwiftUi Navigation Bar Button disappears after entering the third View (Controller)

我对 SwiftUi 有很大的疑问。非常简单的 NavigationView 层次结构中的“后退按钮”在第三个视图中消失了。如果我再往前看一个视图,后退按钮又在那里,我可以返回。

我搜索了 3 个小时,但只找到了这个 SwiftUI: Back button disappears when clicked on NavigationLink

显然这不能解决我的问题。

感谢您的帮助!

我找到问题了!

NavigationView 上的 .toolbar 修饰符以错误的方式隐藏了后退按钮!

对我来说,问题有点不同 - 只有在与第三个视图交互后,后退按钮才会在第三个视图上消失,例如单击进入列表视图。

我的解决方法是使用旧的 .navigationBarItems 而不是 .toolbar,所以:

 .navigationBarItems(trailing:
    Menu {
       Button(action: {
          //some action
       }) {
          //some label
       }
       Button(action: {
          //some action
       }) {
          //some label
       }                                        
    }
    label: {
       //some label
    }
 )

而不是:

.toolbar {
   ToolbarItem(placement: .navigationBarTrailing) {
      Menu {
         Button(action: {
            //some action
         }) {
            //some label
         }
         Button(action: {
            //some action
         }) {
            //some label
         }                        
      }
      label: {
         //some label
      }
   }
}

我为不想使用已弃用方法的人找到了另一种解决方法。

只需在您的 .toolbar 中添加此 ToolBarItem:

.toolbar {

    // ... other toolbar items

    ToolbarItem(placement: .navigationBarLeading) {
        Text("")
    }
}

另一个解决方案似乎正在 Xcode 12.4:

ToolbarItem(placement: .navigationBarLeading) {
    HStack {}
}

如果您想使代码更简洁

/// A ToolbarItem wrapper to work around the back button disappearance bug in SwiftUI 2.
struct NavbarBackButtonDisappearanceWorkaroundItem: ToolbarContent {
    var body: some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            Color.clear
        }
    }
}

使用如下:

.toolbar {
   NavbarBackButtonDisappearanceWorkaroundItem()
   SomeOtherUsefulItem()        
}

您需要添加到 NavigationView

.navigationViewStyle(StackNavigationViewStyle())

我找到了解决这个问题的方法。如果您既不使用 .toolbar 也不使用 .navigationBarItems,您应该简单地向您添加 .navigationBarItems(trailing: E​​mptyView()) children。这将使您的后退按钮始终保持活动状态)

   var body: some View {
      ScrollView() {
        ...
      }
       .navigationBarItems(trailing: EmptyView())
     }

'''