我在我的应用程序中实现了一个平移手势来解除视图。基本上当用户向下滑动时,视图会消失。
但是,我希望它能够正常工作,以便在用户向下或向下滑动时不会消失。我只希望它能够在严格的垂直向下滑动时做出响应。到目前为止,这是我的代码。
var originalPosition: CGPoint?
var currentPositionTouched: CGPoint?
func panGestureAction(_ panGesture: UIPanGestureRecognizer) {
if currentScreen == 0 {
let translation = panGesture.translation(in: view)
if panGesture.state == .began {
originalPosition = view.center
//currentPositionTouched = panGesture.location(in: view)
} else if panGesture.state == .changed {
view.frame.origin = CGPoint(
x: view.frame.origin.x,
y: view.frame.origin.y + translation.y
)
panGesture.setTranslation(CGPoint.zero, in: self.view)
} else if panGesture.state == .ended {
let velocity = panGesture.velocity(in: view)
if velocity.y >= 150 {
UIView.animate(withDuration: 0.2
, animations: {
self.view.frame.origin = CGPoint(
x: self.view.frame.origin.x,
y: self.view.frame.size.height
)
}, completion: { (isCompleted) in
if isCompleted {
self.dismiss(animated: false, completion: nil)
}
})
} else {
UIView.animate(withDuration: 0.2, animations: {
self.view.center = self.originalPosition!
})
}
}
}
}
答案 0 :(得分:0)
您与currentPositionTouched
走在正确的轨道上。在.began
区块中,将currentPositionTouched
设置为panGesture
的位置
currentPositionTouched = panGesture.location(in: view)
然后,在.changed
和.ended
块中,使用检查来确定x
值是否相同并相应地开发逻辑。
if currentPositionTouched.x == panGesture.location(in: view).x
答案 1 :(得分:0)
您可以使用gestureRecognizerShouldBegin
。您可以将其设置为仅识别垂直手势(即角度小于特定大小的手势)。例如,在Swift中,它是:
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gesture = gestureRecognizer as? UIPanGestureRecognizer else { return false }
let translation = gesture.translation(in: gesture.view!)
if translation.x != 0 || translation.y != 0 {
let angle = atan2(abs(translation.x), translation.y)
return angle < .pi / 8
}
return false
}
}
只需确保设置平移手势识别器的delegate
。
注意,我没有检查它是否绝对垂直(因为手势路径的变化,它可能很少是完全垂直的),但在一定的合理角度内。
仅供参考,这是基于this Objective-C rendition。