【发布时间】:2026-02-09 00:35:01
【问题描述】:
我在尝试使用平移手势识别器拖动视图时遇到问题。该视图是一个collectionViewCell,并且拖动代码正在工作,除非当拖动开始时,视图会向上和向左跳跃。我的代码如下。
在collectionViewCell中:
override func awakeFromNib() {
super.awakeFromNib()
let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(detectPan))
self.gestureRecognizers = [panRecognizer]
}
var firstLocation = CGPoint(x: 0, y: 0)
var lastLocation = CGPoint(x: 0, y: 0)
@objc func detectPan(_ recognizer:UIPanGestureRecognizer) {
switch recognizer.state {
case .began:
firstLocation = recognizer.translation(in: self.superview)
lastLocation = recognizer.translation(in: self.superview)
case .changed:
let translation = recognizer.translation(in: self.superview)
self.center = CGPoint(x: lastLocation.x + translation.x, y: lastLocation.y + translation.y)
default:
UIView.animate(withDuration: 0.1) {
self.center = self.firstLocation
}
}
}
第一张是拖动开始前的画面,第二张是向上拖动时的画面。
【问题讨论】:
-
我相信您的 .changed 案例不应该使用 self.center。
-
@xTwisteDx 我应该改用什么?
-
其实就是用翻译而不是最后一个位置+翻译。试试看.. 抱歉,没有 XCode atm,所以我无法测试。我认为实际上可能发生的是您正在修改设置的最后位置,然后添加翻译。注意视图向上和向左。这表明它在计算某些东西。
-
@xTwisteDx 啊!我想到了。你的第一个猜测是正确的,我应该更新 frame.origin.y 和 frame.origin.x 而不是中心。谢谢!
标签: ios swift uicollectionview uicollectionviewcell uipangesturerecognizer