简体   繁体   English

在 SwiftUI 中创建自定义导航栏,因此其他 SwiftUI 视图应重用相同的导航栏

[英]Create a custom Navigation Bar in SwiftUI So other SwiftUI views should reuse same Nav Bar

In iOS SwiftUI, How we can make a common layout for Navigation Bar.在 iOS SwiftUI 中,我们如何为导航栏制作通用布局。 So we can use that in all project without re-write the same code.所以我们可以在所有项目中使用它而无需重新编写相同的代码。

在此处输入图像描述

We can use ViewBuilder to create base view for common code as follows:我们可以使用 ViewBuilder 为通用代码创建基本视图,如下所示:

struct BaseView<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
    self.content = content()
}
var body: some View {
    // To-do: The most important part will go here
  }
}

How we can add Navigation bar Code in View Builder or Base view?我们如何在 View Builder 或 Base 视图中添加导航栏代码?

One way to achieve this is to use a custom view as an overlay.实现此目的的一种方法是使用自定义视图作为覆盖。

For example consider the below code which makes a custom navigation bar using overlay:例如,考虑下面的代码,它使用覆盖创建自定义导航栏:

struct Home: View {
    var body: some View {
        ScrollView {
            // Your Content
        }
        .overlay {
            ZStack {
                Color.clear
                    .background(.ultraThinMaterial)
                    .blur(radius: 10)

                Text("Navigation Bar")
                    .font(.largeTitle.weight(.bold))
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.leading, 20)
            }
            .frame(height: 70)
            .frame(maxHeight: .infinity, alignment: .top)
        }
    }
}

The ZStack inside the .overlay will make a view that looks like a navigation bar. .overlay中的 ZStack 将创建一个看起来像导航栏的视图。 You can then move it to its own struct view, add different variables to it and call it from overlay.然后,您可以将其移动到自己的结构视图中,向其中添加不同的变量并从叠加层中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM