swift3.0添加手勢返回,只需在baseViewController的viewDidLoad中添加如下代碼

只對目前需求進行記錄,有問題請大神指出

借鑒自分貝丶博客:http://blog.csdn.net/meiwenjie110/article/details/70331880

class BaseNavigationController: UINavigationController {

override func viewDidLoad() {

super.viewDidLoad()

/*

分析:一般用手勢觸發某個行為需要哪些條件?

1、需要創建一個我們需要的手勢實例;

2、添加到一個View上(需要一個view);

3、需要一個Target;

4、需要一個Action。

let tapG = UITapGestureRecognizer()

view.addGestureRecognizer(tapG)

tapG.addTarget(<#T##target: Any##Any#>, action: <#T##Selector#>)

我們需要改成全屏觸發,其實Target和Action是不需要改的,那我們就先拿到Target和Action。

再拿到手勢和添加手勢的View,嘗試的去改手勢和添加手勢的View。

總結:從iOS 7.0系統就幫我添加了手勢返回,但是只支持左邊緣觸發,現在我們需要改成全屏觸發,只要把系統的手勢更換為UIPanGestureRecognizer.

*/

//獲取系統的Pop手勢

guard let systemGes =self.navigationController?.interactivePopGestureRecognizer else{return}

print(systemGes)

//獲取系統手勢添加的view

guard let gesView = systemGes.view else{return}

//獲取Target和Action,但是系統并沒有暴露相關屬性

//利用class_copyIvarList查看所有的屬性(發現_targets是一個數組)

print("------------------------屬性---------------------------------")

varivarCount :UInt32=0

let ivars =class_copyIvarList(UIGestureRecognizer.self, &ivarCount)!

for i in0..

letivar = ivars[Int(i)]

letname =ivar_getName(ivar)

print(String(cString: name!))

}

print("------------------------方法---------------------------------")

//利用class_copyMethodList查看所有的方法(并沒有找到我們想要的方法)

var methodCount :UInt32=0

let methods =class_copyMethodList(UIGestureRecognizer.self, &methodCount)!

for i in0..< methodCount {

let method = methods[Int(i)]

let name =method_getName(method)

print("\(name)")

}

//從Targets取出Target

let targets = systemGes.value(forKey:"_targets")as? [NSObject]

guard let targetObjc = targets?.first else {return}

guard let target = targetObjc.value(forKey:"target") else{return}

//方法名稱獲取Action

let action =Selector(("handleNavigationTransition:"))

let panGes =UIPanGestureRecognizer()

panGes.delegate = self

gesView.addGestureRecognizer(panGes)

panGes.addTarget(target, action: action)

// MARK: - UIGestureRecognizerDelegate

extension BaseNavigationController: UIGestureRecognizerDelegate {

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

//1、由于在主頁面使用手勢會造成pushBUG,因此此處限制主頁面手勢 2、解決網頁向左劃BUG

guard let viewControllers = self.navigationController?.viewControllers else {

return false

}

if (viewControllers.last?.isKind(of: WKWebViewController.classForCoder()))!, let ges = gestureRecognizer as? UIPanGestureRecognizer {

if ges.translation(in: self.view).x < 0 {//<0向左劃

return false

}

}

return viewControllers.count > 1

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容