Iphone 为UIView图层设置定位点
我有一个UIView子类,我希望能够在它的superview中移动。当用户在Iphone 为UIView图层设置定位点,iphone,objective-c,uiview,Iphone,Objective C,Uiview,我有一个UIView子类,我希望能够在它的superview中移动。当用户在self.center之外但在self.bounds范围内的某个地方触摸UIView时,它会“跳转”,因为我将新位置添加到self.center以实现实际移动。为了避免这种行为,我尝试设置一个锚定点,让用户在视图边界内的任何位置抓取并拖动视图 我的问题是,当我计算新的锚定点(如下面的代码所示)时,什么都没有发生,视图根本不会改变位置。另一方面,如果我将锚点设置为预先计算的点,我可以移动视图(当然,它会“跳”到预先计算的点
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;
}
您应该仅在TouchBegin上更新主播点。如果一直重新计算(TouchMoved),子视图不移动是合乎逻辑的 正如Kris Van Bael所指出的,您需要在
TouchStart:withEvent:
方法中进行锚点计算,以避免否定运动。此外,由于更改图层的锚定点
将移动视图的初始位置,因此必须向视图的中心
点添加偏移,以避免第一次触摸后出现“跳跃”
您可以根据初始和最终锚点之间的差值(乘以视图的宽度/高度)计算(并添加到视图的中心
点)偏移,或者将视图的中心
设置为初始接触点
也许是这样的:
- (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;
}
更多关于苹果文档中主播点的信息和我提到的一个类似的SO问题。谢谢,当然你是对的!此外,重新计算锚点显然没有意义,因为当实际移动开始时,用户不会在边界内移动手指。但是,将anchorPoint的更新更改为TouhesBegind确实会出现偏移问题,因为Sam在其回答中强调了这一点。请确保您完全理解anchorPoint: