我希望2个视图的行为就好像它们是“一个视图” - 意味着视图1在'x'n个像素上移动我希望视图2移动x轴的像素数量相同(任意方向) - 无需计算各种偏移量等等。如何附加2个视图以便它们可以作为一个视图平移
我想用新的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轴和“硬”彼此连接 - 任何方式来做到这一点?
而且不要忘了对上海华和上海华盈的Alpha设置平移手势识别为0 –
我希望我可以添加这两个观点对同样的层面 - 但这是不可能的 - 一个视图属于一个表视图 - 另一个属于一个容器 - 所以他们确实没有任何关系或者彼此之间的知识 - 这个例子仅用于演示目的(因为我正在玩它)。目标是让两个视图一起移动 - 自动布局是不可能的 - 我现在正在做的是手动将'view2'的原点改为'x'个像素 - 但这是不稳定的,并且看起来不太好:( –
In在这种情况下,我认为没有一种简单的方法可以省略手动更改原点。您可以考虑[KVO](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving。 html)(这里简单的解释)(http://nshipster.com/key-value-observing/))来观察视图的起源何时改变,但如果它是'UITableViewCell',它可能由于电池重复使用而使您陷入困境。 –