基本上,我想要做的是移动视图以跟随用户的平移。只要使用相同的平移对象,这就可以正常工作。问题出现在用户发布而不是启动另一个平底锅时。
根据文档,translationInView
中的值是相对于平底锅开头的位置。
所以我处理这个问题的策略是在视图中添加两个属性,这样我就可以判断是否使用了相同的pan对象以及参考位置是什么。 self
对象是要移动的对象。它是一个UIView子类。
CGPoint originalPoint;
if (pan == self.panObject) {
//If the pan object is the same as the one in the property, use the saved value as the reference point.
originalPoint = CGPointMake(self.panStartLocation.x, self.panStartLocation.y);
} else {
//If the pan object is DIFFERENT, set the originalPoint from the existing center.
//self.center is in self.superview's coordinate system.
originalPoint = CGPointMake(self.center.x, self.center.y);
self.panStartLocation = CGPointMake(originalPoint.x, originalPoint.y);
self.panObject = pan;
}
CGPoint translation = [pan translationInView:self.superview];
self.center = CGPointMake(originalPoint.x+translation.x, originalPoint.y+translation.y);
此方案不起作用,因为每个pan对象显然是同一个对象。我花了一些时间在调试器中验证这一点,这似乎是真的。我认为pan对象每次触摸都会有所不同。因为这不起作用,有什么替代方案?
答案 0 :(得分:1)
我解决了。这是更正后的代码:
CGPoint originalPoint;
if (pan.state == UIGestureRecognizerStateBegan) {
originalPoint = CGPointMake(self.center.x, self.center.y);
self.panStartLocation = CGPointMake(originalPoint.x, originalPoint.y);
} else {
originalPoint = CGPointMake(self.panStartLocation.x, self.panStartLocation.y);
}
CGPoint translation = [pan translationInView:self.superview];
self.center = CGPointMake(originalPoint.x+translation.x, originalPoint.y+translation.y);
编辑:更好的方法是利用手势识别器允许您设置翻译的事实:
[sender setTranslation:CGPointMake(0.0, 0.0) inView:self.pieceBeingMoved];
移动项目时执行此操作,然后下次的新翻译将相对于您刚搬到的位置。