2014-07-08 102 views
1

我试图通过使用自动布局拖动另一个视图来移动一个视图。我的场景是这样的:如何在拖动其他视图时移动一个视图

Scene with upper view which is desired to be dragged by touch and the view below which should follow the view above

这块绿松石的观点是,我想触摸它和下面的红色是应该遵循的,我拖动图的图拖动一个视图。我添加这些视图是垂直间距约束具有恒定等于0

我加入定时器,每秒移动上部小图的一个像素但不幸的是红色的是仍然在同一个地方之间的约束。

@implementation ViewController { 
    NSTimer *_timer; 
} 

- (IBAction)onDragButtonPressed:(id)sender { 
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_onDrag) userInfo:nil repeats:YES]; 
} 


- (void)_onDrag { 
    self.draggable.center = CGPointMake(self.draggable.center.x, self.draggable.center.y - 1); 
    [self.dragged setNeedsDisplay]; 
} 

我也试图与定制约束是这样的:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.dragged attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.draggable attribute:NSLayoutAttributeBottom multiplier:1 constant:0]; 
[self.view addConstraint:constraint]; 

但没有任何积极的结果。

我应该怎么做才能正确实现这种行为?

预先感谢您。

+0

绿松石视图还有什么其他约束? – duci9y

+0

我选择了该视图,以便您可以查看该视图的所有约束。它具有水平居中约束以及宽度和高度。底部的红色视图有约束优先级为250的超级视图底部。没有这个限制,这也不起作用。红色也有宽度,高度,前导和尾随设置为0. –

回答

2

使用AutoLayout时,会丢失帧和中心。相反,您依靠NSLayoutConstraints的常数值。所以,你的代码,需要改变的是在这里:

- (void)_onDrag { 
    self.draggable.center = CGPointMake(self.draggable.center.x, self.draggable.center.y - 1); 
    [self.dragged setNeedsDisplay]; 
} 

让更多的东西一样

- (void)_onDrag:(UIPanGestureRecognizer *)gesture { 
    self.draggableConstraint.constant = [gesture locationInView:self.view].y; 
    [self.view layoutIfNeeded]; 
} 

注意UIPanGestureRecognizer。您应该考虑使用设计用于移动视图的手势识别器的简单视图,而不是按钮。然后,您的​​3210方法可以询问触摸的手势,并相应地更新self.draggableConstraint。您可能需要进行一些调整,例如constant = (GESTURE LOCATION Y) - (DRAGGABLE STARTING Y);来处理偏移量。这里的魔术酱是你坚持一个约束,然后在调用-[UIView layoutIfNeeded]之前改变它的常量,这会触发立即重新计算所有约束。

+0

谢谢你的帮助。它正在工作:) –

+0

随时。快乐编码:) –

相关问题