躲藏NavigationBarBackButton时,完成右滑封闭页面
导言:现在的大多数iOS App都有右滑封闭页面的功能,众多iPhone用户也都习惯了这种操作
当运用体系自带的NavigationBarBackButton时能够很轻松完成这个功能,但体系自带的BackButton通常会带上个页面的Title,并且需求通常需要自定义NavigationBar,就需要躲藏体系自带的回来摁钮,这时右滑回来的功能也消失了,这非常头疼
1.先看运用体系回来摁钮时操作
代码:
import SwiftUI
//父页面
struct IndexView: View {
var body: some View {
NavigationView{
VStack {
NavigationLink {
ChildView()
} label: {
Text("jump to ChileView")
}
}
.navigationBarTitle("主页", displayMode: .inline)
}
}
}
//子页面
struct ChildView: View {
var body: some View {
VStack {
Text("ChildView")
}
.navigationBarTitle("子页面", displayMode: .inline)
}
}
ps:能够发现子页面的回来摁钮会显示父页面的title,这通常是不符合页面UI的需求,但此时是能够满意右滑跳转的
2.当躲藏掉回来Button时操作
代码:
import SwiftUI
//父页面
struct IndexView: View {
var body: some View {
NavigationView{
VStack {
NavigationLink {
ChildView()
} label: {
Text("jump to ChileView")
}
}
.navigationBarTitle("主页", displayMode: .inline)
}
}
}
//子页面
struct ChildView: View {
@Environment(.presentationMode) var presentionation //点了确认后 让本页面封闭消失的变量
var body: some View {
VStack {
Text("ChildView")
}
.navigationBarTitle("子页面", displayMode: .inline)
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading:
Button(action: {
self.presentionation.wrappedValue.dismiss()
}, label: {
Image(systemName: "chevron.left")
.foregroundColor(Color.black)
})
)
}
}
ps:这时咱们能够满意UI的需求和规划,可是右滑回来的功能跟着BackButton一起躲藏掉了,这时功能就出现了缺失
3.这时候只需要给UINavigationController添加额外的署理和办法即可完成
新增署理代码:
import SwiftUI
//右滑回来
extension UINavigationController: UIGestureRecognizerDelegate {
override open func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
原代码不变:
import SwiftUI
//父页面
struct IndexView: View {
var body: some View {
NavigationView{
VStack {
NavigationLink {
ChildView()
} label: {
Text("jump to ChileView")
}
}
.navigationBarTitle("主页", displayMode: .inline)
}
}
}
//子页面
struct ChildView: View {
@Environment(.presentationMode) var presentionation //点了确认后 让本页面封闭消失的变量
var body: some View {
VStack {
Text("ChildView")
}
.navigationBarTitle("子页面", displayMode: .inline)
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading:
Button(action: {
self.presentionation.wrappedValue.dismiss()
}, label: {
Image(systemName: "chevron.left")
.foregroundColor(Color.black)
})
)
}
}