文字列から釘にぶら下がっている額縁である 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)];
}];
}
itemBehavior の angularForce として motion.gravity.x を試して、力が正しく返され、ビューが正しい方向に回転することを確認しました。これはすべて問題ないようです。このアプローチの問題は、一定の力が適用されるため、ビューが回転し続けることです。setGravityDirection: を使用すると、ビューが回転せずに固定されます。いくつかの助けをいただければ幸いです!ありがとう!