将平移手势限制在一个方向
Limiting pan gesture to one direction
希望图像只向上平移。
我已尝试编辑 x 和 y 坐标。试图根据翻译创建一个新的 y 变量但没有改变。
@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer) {
let translation: CGPoint = recognizer.translation(in: self.view)
var newY = view.center.y + translation.y
startingPoint = recognizer.view!.center
recognizer.view?.superview?.bringSubviewToFront(recognizer.view!)
if newY > translation.y
{
recognizer.view?.center = CGPoint(x: recognizer.view!.center.x, y: recognizer.view!.center.y + translation.y)
newY = view.center.y + translation.y
recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
//startingPoint = recognizer.view!.center
}
它会上下摇动,但我只希望它向上移动。
您正在比较错误的变量,Y
值向下增加。您需要检查的是 transition.y
是否为负数(即向上移动):
替换为:
if newY > translation.y
有了这个:
if transition.y < 0
事实上,根本不需要newY
:
@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
guard let view = recognizer.view else { return }
view.superview?.bringSubviewToFront(view)
// If the movement is upward (-Y direction):
if translation.y < 0
{
view.center = CGPoint(x: view.center.x, y: view.center.y + translation.y)
recognizer.setTranslation(.zero, in: self.view)
}
}
备注:
所做的其他更改:
- 使用
guard
安全解包 recognizer.view
一次,而不是在整个代码中重复解包。
- 将
CGPoint(x: 0, y: 0)
替换为 .zero
,Swift 推断为 CGPoint.zero
,因为它期望 CGPoint
.
希望图像只向上平移。
我已尝试编辑 x 和 y 坐标。试图根据翻译创建一个新的 y 变量但没有改变。
@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer) {
let translation: CGPoint = recognizer.translation(in: self.view)
var newY = view.center.y + translation.y
startingPoint = recognizer.view!.center
recognizer.view?.superview?.bringSubviewToFront(recognizer.view!)
if newY > translation.y
{
recognizer.view?.center = CGPoint(x: recognizer.view!.center.x, y: recognizer.view!.center.y + translation.y)
newY = view.center.y + translation.y
recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
//startingPoint = recognizer.view!.center
}
它会上下摇动,但我只希望它向上移动。
您正在比较错误的变量,Y
值向下增加。您需要检查的是 transition.y
是否为负数(即向上移动):
替换为:
if newY > translation.y
有了这个:
if transition.y < 0
事实上,根本不需要newY
:
@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
guard let view = recognizer.view else { return }
view.superview?.bringSubviewToFront(view)
// If the movement is upward (-Y direction):
if translation.y < 0
{
view.center = CGPoint(x: view.center.x, y: view.center.y + translation.y)
recognizer.setTranslation(.zero, in: self.view)
}
}
备注:
所做的其他更改:
- 使用
guard
安全解包recognizer.view
一次,而不是在整个代码中重复解包。 - 将
CGPoint(x: 0, y: 0)
替换为.zero
,Swift 推断为CGPoint.zero
,因为它期望CGPoint
.