我使用以下代码在我的WebView中使用UIScreenEdgePanGestureRecognizer
返回和转发:
class FirstViewController: UIViewController {
@IBOutlet var homewebview: UIWebView!
// create left edge and right edge gesture
let leftEdgePanGesture = UIScreenEdgePanGestureRecognizer()
let rightEdgePanGesture = UIScreenEdgePanGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
// add target for gesture
self.leftEdgePanGesture.addTarget(self, action: #selector(FirstViewController.handleLeftEdge(_:)))
self.rightEdgePanGesture.addTarget(self, action: #selector(FirstViewController.handleRightEdge(_:)))
// set detection edge
self.leftEdgePanGesture.edges = UIRectEdge.Left
self.rightEdgePanGesture.edges = UIRectEdge.Right
// add gesture into view
self.view.addGestureRecognizer(self.leftEdgePanGesture)
self.view.addGestureRecognizer(self.rightEdgePanGesture)
}
func handleLeftEdge( gesture: UIScreenEdgePanGestureRecognizer ) {
homewebview.goBack()
}
// perform operation when right edge gesture detected
func handleRightEdge( gesture: UIScreenEdgePanGestureRecognizer ) {
homewebview.goForward()
}
}
我的问题是它多次触发。它不会返回/转发一个网页,它会返回/转发ca. 5个网页。
有什么解决方案吗?或者我必须使用UISwipeGestureRecognizer
。我宁愿不想使用UISwipeGestureRecognizer
因为它没有像UIScreenEdgePanGestureRecognizer
那样可靠地做出反应。 UISwipeGestureRecognizer
有时"认为"我想在我的WebView中垂直滚动并且没有反应。或者有解决方案吗?
答案 0 :(得分:3)
平移手势识别器会在其状态发生变化时调用处理程序方法。这包括它开始,结束和介于两者之间的每一个动作。在处理程序内部,您需要检查手势识别器的状态并决定要做什么。
您希望每个手势只触发一次代码,并且只有在触摸移动超过阈值量时才想执行此操作。
class ViewController: UIViewController {
let leftEdgePanGesture = UIScreenEdgePanGestureRecognizer()
var leftPanTriggered: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
leftEdgePanGesture.addTarget(self, action: #selector(handleLeftEdge(_:)))
leftEdgePanGesture.edges = .Left
view.addGestureRecognizer(leftEdgePanGesture)
}
func handleLeftEdge(gesture: UIScreenEdgePanGestureRecognizer) {
switch gesture.state {
case .Began, .Changed:
if !leftPanTriggered {
let threshold: CGFloat = 10 // you decide this
let translation = abs(gesture.translationInView(view).x)
if translation >= threshold {
performLeftGesture()
leftPanTriggered = true
}
}
case .Ended, .Failed, .Cancelled:
leftPanTriggered = false
default: break
}
}
func performLeftGesture() {
homewebview.goBack()
}
}