Osk*_*kar 6 iphone objective-c uiview
我有一个UIView子类,我希望能够在它的superview中移动.当用户在外面某处触摸UIView self.center但在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;
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 13
正如Kris Van Bael指出的那样,你需要在touchsBegan:withEvent:方法中进行锚点计算,以免否定运动.此外,由于更改图层anchorPoint将移动视图的初始位置,因此您必须向视图的center点添加偏移以避免在第一次触摸后"跳转".
您可以通过根据center初始和最终anchorPoints之间的差异(乘以视图的宽度/高度)计算(并添加到视图的点)偏移量,或者可以将视图设置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;
}
Run Code Online (Sandbox Code Playgroud)
关于更多信息anchorPoint从苹果的文档的位置和相似,所以怀疑我引用在这里.
| 归档时间: |
|
| 查看次数: |
28757 次 |
| 最近记录: |