手势
lazy var pag: UIPanGestureRecognizer = {
let target = self.navigationController?.interactivePopGestureRecognizer?.delegate
varpag =UIPanGestureRecognizer.init(target:target , action:Selector(("handleNavigationTransition:")))
pag.delegate=self
returnpag
}()
添加手势
view.addGestureRecognizer(pag)
extension UIViewController:UIGestureRecognizerDelegate{
/// 允许手势 开始识别
publicfuncgestureRecognizerShouldBegin(_gestureRecognizer:UIGestureRecognizer) ->Bool{
if navigationController?.children.count == 1 {
return false
}
return true
}
}
// 完整代码
// twoVC.swift
// text
//
// Created by summer on 2019/12/14.
// Copyright © 2019 summer. All rights reserved.
//
importUIKit
class twoVC: UIViewController {
lazyvarbackButton:UIButton= {
var backButton = UIButton.init(type: UIButton.ButtonType.custom)
backButton.setTitle("返回", for:UIControl.State.normal)
backButton.frame.size=CGSize.init(width:UIScreen.main.bounds.width, height:40)
backButton.frame.origin=CGPoint.init(x:0, y:80)
backButton.addTarget(self, action:#selector(backAcion), for:UIControl.Event.touchUpInside)
backButton.backgroundColor = UIColor.blue
backButton.titleLabel?.textAlignment = .left
returnbackButton
}()
lazy var pag: UIPanGestureRecognizer = {
let target = self.navigationController?.interactivePopGestureRecognizer?.delegate
varpag =UIPanGestureRecognizer.init(target:target , action:Selector(("handleNavigationTransition:")))
pag.delegate=self
returnpag
}()
var navigationDelegete : UIGestureRecognizerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
initSet()
view.backgroundColor = UIColor.orange
}
/// 手势设置代理放在这里,否则侧滑时放弃侧测就是时, viewWillDisappear会调用,再回来时手势说失效了
overridefuncviewWillAppear(_animated:Bool) {
super.viewWillAppear(animated)
///保存上层控制器代理
self.navigationDelegete = self.navigationController?.interactivePopGestureRecognizer?.delegate
/// 侧滑时不导航条不闪烁
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
overridefuncviewWillDisappear(_animated:Bool) {
super.viewWillDisappear(animated)
///恢复导航控制器代理
self.navigationController?.interactivePopGestureRecognizer?.delegate = self.navigationDelegete
/// 侧滑时不导航条不闪烁
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
@objcfuncbackAcion() {
navigationController?.popViewController(animated: true)
}
funcinitSet() {
view.addSubview(backButton)
title="\(self.self)"
view.addGestureRecognizer(pag)
}
}
extension UIViewController:UIGestureRecognizerDelegate{
/// 允许手势 开始识别
publicfuncgestureRecognizerShouldBegin(_gestureRecognizer:UIGestureRecognizer) ->Bool{
if navigationController?.children.count == 1 {
returnfalse
}
return true
}
/// 允许多个手势,识别
publicfuncgestureRecognizer(_gestureRecognizer:UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer:UIGestureRecognizer) ->Bool{
returntrue
}
}