我希望 2 个视图表现得好像它们是“一个视图”——这意味着如果视图 1 在“x”n 个像素上移动,我希望视图 2 在 x 轴上移动相同数量的像素(在任何任意方向上)——没有必须计算各种偏移量等等。
我认为使用新的UIDynamicAnimator
会是一个很好的选择,所以我尝试了这个
UIView *v1 = [[UIView alloc] initWithFrame:CGRectMake(320-150, 150, 150, 100)];
v1.backgroundColor = [UIColor blackColor];
[self.view addSubview:v1];
self.v1 = v1;
UIView *v2 = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width,
0,
self.view.bounds.size.width,
self.view.bounds.size.height)];
v2.backgroundColor = [UIColor redColor];
[self.view addSubview:v2];
self.v2 = v2;
UIPanGestureRecognizer *p =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[v1 addGestureRecognizer:p];
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIAttachmentBehavior *att =
[[UIAttachmentBehavior alloc] initWithItem:self.v1
offsetFromCenter:UIOffsetZero
attachedToItem:self.v2
offsetFromCenter:UIOffsetMake(0,
self.v1.center.y - self.v2.center.y)];
att.damping = 0;
[self.animator addBehavior:att];
self.att = att;
-(void)pan:(UIPanGestureRecognizer *)gesture {
if(gesture.state == UIGestureRecognizerStateChanged) {
CGPoint p = [gesture locationInView:self.view];
// move only on x axis but keep on same y point
self.v1.center = CGPointMake(p.x, self.v1.center.y);
[self.animator updateItemUsingCurrentState:self.v1];
}
}
但它们是相互作用的——小视图倾斜并改变它的旋转和 y 位置。
我本来希望 - 仅在 1 个轴上并且彼此“硬”连接 - 有什么方法可以做到这一点?