我试图手动更改UIDynamics中视图的旋转,但是更新后视图的旋转总是重置的。文档说,UIDynamicAnimator的updateItemUsingCurrentState:方法应该更新项目的位置和旋转,但只更新位置。
我创造了一个很短的例子,一个方形的视图从屏幕上掉下来,触摸后,它应该被定位到触摸的位置,旋转到45度。然而,不发生旋转(有时可以看到旋转仅一秒钟,但在此之后又会被重置):
#import "ViewController.h"
@interface ViewController ()
{
UIDynamicAnimator* _animator;
UIView* _square;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_square = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
_square.backgroundColor = [UIColor grayColor];
[self.view addSubview:_square];
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[_square]];
gravityBehavior.magnitude = 0.1;
[_animator addBehavior:gravityBehavior];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
_square.center = [touch locationInView:self.view];
NSLog(@"transform before rotation: %@", NSStringFromCGAffineTransform(_square.transform));
_square.transform = CGAffineTransformMakeRotation(M_PI/4);
[_animator updateItemUsingCurrentState:_square];
NSLog(@"transform after rotation: %@", NSStringFromCGAffineTransform(_square.transform));
}
@end(我把所有的代码都留在这里了,这样您就可以将其复制粘贴到新创建的项目中。希望没有太多不相关的代码让人感到不安)
那我是不是做错什么了?或者不可能显式地改变视图的旋转?
发布于 2014-09-09 13:50:49
基于无限詹姆斯的回答,我找到了一个很好的解决方案。因此,要更新项目的轮换,您需要
备注:您可以将所有行为作为子行为添加到父行为中,这样您就可以立即删除并返回所有行为(但是这种态度会阻止动态动画中的所有动作,因此您还应该考虑其他危害较小的方式)。
- (void)rotateItem:(UICollectionViewLayoutAttributes *)item toAngle:(CGFloat)angle
{
CGPoint center = item.center;
[self.dynamicAnimator removeBehavior:self.parentBehavior];
item.transform = CGAffineTransformMakeRotation(angle);
[self.dynamicAnimator addBehavior:self.parentBehavior];
}这个解决方案是一种妥协,因为它停止了项目的移动,所以如果您发现更好的东西,请添加您的答案。
发布于 2014-09-05 12:12:28
我的解决方案是从动画师中删除行为,然后用项的修改状态重新创建行为。明确地设置一个项目的位置(通过center)和旋转不是真正应该做的事情,而它是在UIDynamics的影响下(就像在酒精的影响下,但更无聊)。
我的解决方案的代码:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.animator removeBehavior:self.gravityBehavior];
self.gravityBehavior = nil;
UITouch *touch = touches.anyObject;
CGPoint touchLocation = [touch locationInView:touch.view];
self.square.center = touchLocation
self.square.transform = CGAffineTransformMakeRotation(M_PI/4);
self.gravityBehavior = [[UIGravityBehavior alloc] initWithItem:self.square];
self.gravityBehavior.magnitude = 0.1f;
[self.animator addBehavior:self.gravityBehavior];
}https://stackoverflow.com/questions/25643594
复制相似问题