【发布时间】:2011-06-16 21:15:39
【问题描述】:
我有一个 UIView 子类,我希望它能够在它的超级视图中移动。当用户在self.center 之外但在self.bounds 内触摸 UIView 时,它会“跳跃”,因为我将新位置添加到 self.center 以实现实际移动。为了避免这种行为,我尝试设置一个锚点,让用户可以抓取并拖动视图范围内的任何位置。
我的问题是,当我计算新的锚点(如下面的代码所示)时,没有任何反应,视图根本不会改变位置。另一方面,如果我将锚点设置为预先计算的点,我可以移动视图(但当然它会“跳转”到预先计算的点)。为什么这不能按预期工作?
谢谢。
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// Only support single touches, anyObject retrieves only one touch
UITouch *touch = [touches anyObject];
CGPoint locationInView = [touch locationInView:self];
// New location is somewhere within the superview
CGPoint locationInSuperview = [touch locationInView:self.superview];
// Set an anchorpoint that acts as starting point for the move
// Doesn't work!
self.layer.anchorPoint = CGPointMake(locationInView.x / self.bounds.size.width, locationInView.y / self.bounds.size.height);
// Does work!
self.layer.anchorPoint = CGPointMake(0.01, 0.0181818);
// Move to new location
self.center = locationInSuperview;
}
【问题讨论】:
-
确保你对anchorPoint有充分的了解:stackoverflow.com/a/22188420/550393
标签: iphone objective-c uiview