设置UIView图层的锚点

时间:2011-01-27 22:06:27

标签: iphone objective-c uiview

我有一个UIView子类,我希望能够在它的superview中移动。当用户在self.center之外的某个地方触摸UIView但在self.bounds之内它会“跳”,因为我将新位置添加到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;
}

2 个答案:

答案 0 :(得分:13)

正如Kris Van Bael指出的那样,你需要在touchsBegan:withEvent:方法中进行锚点计算,以免否定运动。此外,由于更改图层的anchorPoint将移动视图的初始位置,因此您必须向视图的center点添加偏移量,以避免在第一次触摸后出现“跳转”。

你可以根据初始和最终的anchorPoints(乘以你的视图的宽度/高度)之间的差异来计算(并添加你的视图的center点)偏移,或者你可以设置视图{ {1}}到初始接触点。

或许这样的事情:

center

有关- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint locationInView = [touch locationInView:self]; CGPoint locationInSuperview = [touch locationInView:self.superview]; self.layer.anchorPoint = CGPointMake(locationInView.x / self.frame.size.width, locationInView.y / self.frame.size.height); self.center = locationInSuperview; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint locationInSuperview = [touch locationInView:self.superview]; self.center = locationInSuperview; } 的更多信息来自苹果的文档here以及类似的问题,我引用了here

答案 1 :(得分:0)

您应该只在TouchBegin上更新anchorpoint。如果您一直重新计算(TouchMoved),则子视图不会移动是合乎逻辑的。