【问题标题】:Create a common layout for the navigation bar in SwiftUI, so other SwiftUI views should reuse same Nav Bar在 SwiftUI 中为导航栏创建通用布局因此其他 SwiftUI 视图应该重用相同的导航栏
【发布时间】:2022-10-18 21:03:51
【问题描述】:

在 iOS SwiftUI 中,我们如何为 Navigation Bar 制作通用布局。所以我们可以在所有项目中使用它而无需重新编写相同的代码。

我们可以使用 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
  }
}

我们如何在 View Builder 或 Base 视图中添加导航栏代码?

【问题讨论】:

  • 您是否尝试在不同的结构视图中定义导航栏并将其用作不同视图中的覆盖?
  • 不,我没有尝试过这种方法。我曾尝试在基本视图中添加导航栏,但这种方法不起作用。

标签: ios swift swiftui swiftui-navigationview


【解决方案1】:

实现此目的的一种方法是使用自定义视图作为覆盖。

例如,考虑下面的代码,它使用覆盖创建自定义导航栏:

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

.overlay 中的 ZStack 将创建一个看起来像导航栏的视图。然后,您可以将其移动到自己的结构视图中,向其中添加不同的变量并从叠加层中调用它。

【讨论】:

  • 感谢@arata 的回复,我们可以在导航视图上编写一些包装器吗?因此,如果需要,我们可以利用某些类中的默认导航栏功能。
  • @GrayFox那么,您想修改默认导航栏而不是从头开始制作一个新导航栏吗? (这道题在某种程度上也是类似的问题)stackoverflow.com/questions/57686218/…
  • 是的@arata,如果我们使用现有的导航栏而不是创建一个新的导航栏会更好。
  • 是的@arata,在那个问题中[stackoverflow.com/questions/57686218/… View Modifier 用于创建基本视图,但如果可能的话,我想重用导航栏。
  • @GrayFox 很有趣,从来没有这样想过。也许有人可以回答你的问题。
【解决方案2】:

您可以像这样创建view 的扩展名。您可以查看my blog entry for details

import SwiftUI
extension View {
/// CommonAppBar
public func appBar(title: String, backButtonAction: @escaping() -> Void) -> some View {
    
    self
        .navigationTitle(title)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .navigationBarItems(leading: Button(action: {
            backButtonAction()
        }) {
            Image("ic-back") // set backbutton image here
                .renderingMode(.template)
                .foregroundColor(Colors.AppColors.GrayscaleGray2)
        })
    }
}

现在你可以在视图的任何地方使用这个 appBar

struct TransactionsView: View {
@Environment(.presentationMode) var mode: Binding<PresentationMode>

var body: some View {
    VStack(spacing: 0) {
        
    }
    .appBar(title: "Atiar Talukdar") {
        self.mode.wrappedValue.dismiss()
    }
}
}

struct TransactionsView_Previews: PreviewProvider {
    static var previews: some View {
        TransactionsView()
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2021-02-20
    相关资源
    最近更新 更多