使用Pan Gesture更新视图的NSLayoutConstraint

时间:2014-11-12 11:13:58

标签: ios objective-c autolayout nslayoutconstraint

我有一个UIView,我添加了许多UIImageView s(示例5,数字是动态的)作为子视图。 所有UIImageViews都添加了NSLayoutConstraint(sizeToFit和与superView中心相关的中心)。所有与中心相关的约束都会添加到UIView(父视图)。

每个UIImageView都有一个panGesture。所以当我移动UIImageView时,必须更新UIImageView的中心相关约束。

问题是,

如何识别移动UIImageView的约束?

(我是否需要保留所有已创建约束的引用?还是有其他方法可以执行此操作?)

修改:我的解决方法

谢谢@Lord Zsolt的回答。 我写了下面的代码(我的问题的解决方案)。它可能对有同样问题的其他人有帮助。

定义为全局变量

NSLayoutConstraint *selectedImageViewCenterXconstraint, *selectedImageViewCenterYconstraint;

然后UIPanGestureRecognizer选择器方法是:

-(void)moveImageView:(UIPanGestureRecognizer *)recognizer{

    UIImageView *senderView = (UIImageView*)recognizer.view;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        selectedImageViewCenterXconstraint = nil;
        selectedImageViewCenterYconstraint = nil;
        NSArray *viewConstraints = self.view.constraints;
        for (NSLayoutConstraint *constraint in viewConstraints) {
            if ([constraint.firstItem isEqual:senderView]) {
                if (constraint.firstAttribute == NSLayoutAttributeCenterX) {
                    NSLog(@"gotCenterX");
                    selectedImageViewCenterXconstraint = constraint;
                }else if (constraint.firstAttribute == NSLayoutAttributeCenterY) {
                    NSLog(@"gotCenterY");
                    selectedImageViewCenterYconstraint = constraint;
                }
            }

            if (selectedImageViewCenterXconstraint && selectedImageViewCenterYconstraint) {
                break;
            }
        }
    }


    CGPoint translation = [recognizer translationInView:senderView.superview];

    CGFloat newXconst,newYconst;
    newXconst = selectedImageViewCenterXconstraint.constant + translation.x;
    newYconst = selectedImageViewCenterYconstraint.constant + translation.y;

    selectedImageViewCenterXconstraint.constant = newXconst;
    selectedImageViewCenterYconstraint.constant = newYconst;
    [self.view layoutIfNeeded];

    [recognizer setTranslation:CGPointMake(0, 0) inView:senderView.superview];
} 

1 个答案:

答案 0 :(得分:3)

UIView子类有一个属性constraints,它为您提供了NSArray,其中包含添加到该视图中的约束。

您可以在该数组中搜索您的约束,并验证firstItemlastItemUIImageView

代码示例:

//Assuming self is a view controller.
NSArray *constraints = [self.view constraints];
for (NSLayoutConstraint *constraint in constraints) {
    if (constraint.firstItem == myImageView ||
        constraint.secondItem == myImageView) {
        NSLog(@"Constraint belongs to myImageView");
    }
}