我有一个 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 上的 angularForce 来验证力是否正确返回,并且视图旋转正确的方向,这一切似乎都很好。这种方法的问题是视图继续旋转,因为施加了恒定的力。使用 setGravityDirection: 结果,视图锚定没有旋转。一些帮助将不胜感激!谢谢!