自定义导航栏
隐藏系统导航栏,使用自定义按钮放置在导航栏上。
- use
.navigationBarBackButtonHidden()
modifier to hide the system Back button - add
@Environment(\.presentationMode) var presentation
to the View, so it can be dismissed in code - add a replacement back button to the navigation bar which performs
self.presentation.wrappedValue.dismiss()
这个方案最大的问题是覆盖系统标准的导航返回按钮。因此默认的侧滑返回手势和长按返回按钮显示层级的行为就没有了。
完整代码:
struct DetailView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
Text("Detail View")
.navigationTitle("Detail Title")
.navigationBarBackButtonHidden(true)
// 1
.toolbar {
// 2
ToolbarItem(placement: .navigationBarLeading) {
Button {
// 3
dismiss()
} label: {
// 4
HStack {
Image(systemName: "arrow.backward")
Text("Custom Back")
}
}
}
}
}
}
修改 UINavigationBar appearance
SwiftUI 没有提供接口修改导航栏返回按钮的接口。
但是目前 SwiftUI 的导航使用的是 UIKit 的 NavigationBar,因此可以使用 appearance 进行设置:
UINavigationBar.appearance().backIndicatorImage = UIImage(systemName: "arrow.backward")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(systemName: "arrow.backward")
位置
通过这种方式无法调节图片的位置,因此想要调节 padding 只能通过图标的素材图片里增加空白边距实现。
在这之前需要先说明一下默认返回图标的位置。默认的是距离左边 8,右边6,具体底部11。最小高度18。
如果高度变化,距离底部的边距是固定的。