使用 CMMotionManager 中的 UIDynamics 和重力旋转 UIView



我有一个UIView,它是一个挂在绳子上的钉子上的相框。我正在尝试围绕其锚点旋转视图,以保持视图的底部平坦(与地面平行(,而不管设备如何旋转。我正在尝试通过使用CMMotionManager和UIDynamics来实现这一点,但今天似乎无法正常工作。下面是一些代码...

- (void)viewDidLoad
{
[super viewDidLoad];
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
CGRect pictureFrameBounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.view.bounds)/2.5f, CGRectGetHeight(self.view.bounds)/5);
UIView *pictureFrame = [[UIView alloc] initWithFrame:pictureFrameBounds];
[pictureFrame setBackgroundColor:[UIColor redColor]];
[self.view addSubview:pictureFrame];
self.gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[pictureFrame]];
self.collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[pictureFrame]];
[self.collisionBehavior setTranslatesReferenceBoundsIntoBoundary:YES];
[self.animator addBehavior:self.collisionBehavior];
CGPoint anchorPoint = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetHeight(self.view.bounds)/8);
self.attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:pictureFrame
                                                    offsetFromCenter:UIOffsetMake(0.0f, -CGRectGetHeight(pictureFrame.bounds)/2.5f)
                                                    attachedToAnchor:anchorPoint];
[self.attachmentBehavior setDamping:0];
[self.attachmentBehavior setLength:0];
[self.attachmentBehavior setFrequency:0];
[self.animator addBehavior:self.attachmentBehavior];
UIDynamicItemBehavior *itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[pictureFrame]];
[itemBehavior setAllowsRotation:YES];
[self.animator addBehavior:itemBehavior];
NSOperationQueue* motionQueue = [NSOperationQueue new];
 self.motionManager = [[CMMotionManager alloc] init];
[self.motionManager startDeviceMotionUpdatesToQueue:motionQueue
                                        withHandler:^(CMDeviceMotion *motion, NSError *error) {
                                           [self.gravityBehavior setGravityDirection:CGVectorMake(motion.gravity.x, motion.gravity.y)];
                                        }];
}

我已经尝试将motion.gravity.x作为itemBehavior上的角度力,以验证力是否正确返回,并且视图旋转了正确的方向,一切似乎都很好。这种方法的问题在于视图继续旋转,因为施加了恒定的力。使用 setGravityDirection:结果是视图锚定且没有旋转。一些帮助将不胜感激!谢谢!

尝试将NSOperationQueue更改为mainQueue。这对我有帮助。

[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
[self.gravityBehavior setGravityDirection:CGVectorMake(motion.gravity.x, -(motion.gravity.y))];
}];

希望这也对你有帮助。

相关内容

  • 没有找到相关文章

最新更新