我正在开发一个项目,需要定制导航栏并添加自定义按钮和标题样式,同时还需要在主导航部分下方添加辅助视图。
本质上,我想抽象出根据展示风格选择自定义返回按钮的需要。如果以模态视图的形式呈现,则计划显示X图标。如果将其推送到导航视图中,则要显示返回错误。如果是根视图,则要完全隐藏该按钮。
我已经映射了presentationMode
环境变量,但当我访问isPresented
值时,即使在我的应用程序的根视图上,我始终得到true。
这里是我正在开发的大致想法:
import SwiftUI
struct CustomNavigationBar<Content>: View where Content: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
private let title: LocalizedStringKey
private let content: (() -> Content)?
private var backButton: AnyView? {
let button = Button(action: { self.presentationMode.wrappedValue.dismiss() }) {
// custom image extension, just resolves to a back icon
Image.Icons.arrowBack
}
if (presentationMode.wrappedValue.isPresented) {
return AnyView(button)
} else {
return nil
}
}
public init(_ title: LocalizedStringKey, content: (() -> Content)? = nil) {
self.title = title
self.content = content
}
var body: some View {
VStack {
content?()
Divider().foregroundColor(.gray)
}.navigationBarTitle(title, displayMode: .large)
.frame(minHeight: 96)
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: backButton)
}
}
有没有人在使用SwiftUI时能够访问视图在呈现层次结构中的位置,并可以提供一些经验或提示?谢谢!
presentationMode
是一种绑定,允许视图关闭自身。可以使用preferencekey
作为子视图向上发送数据的一种方式。 - New Dev