使用约束移动视图

时间:2014-12-11 01:46:53

标签: ios objective-c swift autolayout nslayoutconstraint

我的视图控制器中有几个视图,当检测到向下滑动时向下移动,然后在检测到向下滑动时向下移动。我通过使用CGRectOffset调整y原点来强制移动视图。我现在已经对IB的观点应用了约束,我不确定最好的方法是移动视图,以便它们最终在iphone 5,6和6+上的正确位置。

目前我正在做这样的事情:

[self.view layoutIfNeeded];

    self.panFrameVerticalConstraint.constant = self.panFrameVerticalConstraint.constant +338;

    [UIView animateWithDuration:5
                     animations:^{
                         [self.view layoutIfNeeded];
                     }];

使用比率更改常数是否更好?因此,对于上面的约束,而不是使用338,这样做会更好:

    self.panFrameVerticalConstraint.constant = self.panFrameVerticalConstraint.constant + (self.panView.frame.size.height/1.680);

    //self.panView.frame.size.height = 568
    //(568/1.680) = 338

1 个答案:

答案 0 :(得分:23)

是的,更改常量时没有问题。这里的事情是你必须适当地设置你的约束。

让我们考虑一个例子。

我在Storyboard中有一个UIView,我想改变它的宽度。其默认宽度为1024

在动画完成后,我们会将其宽度更改为900

按照以下步骤实现此目的:

  1. 选择我们要更新约束的UIView。这里我们需要更新width,因此我们将为width添加约束。
  2. enter image description here

    1. 现在我们可以看到添加到UIView的新约束。
    2. enter image description here

      1. 点击该约束。它将显示约束属性。现在我们要将宽度从1024减小到900,这样在约束属性中将关系属性更改为小于或等于。同样,如果您希望从1024增加宽度,则关系大于或等于
      2. enter image description here

        1. 现在为IBOutlet创建一个NSLayoutConstraint变量,并将其与上述宽度约束相关联。
        2. 变量看起来像:

          在目标C中:

          @property (weak, nonatomic) IBOutlet NSLayoutConstraint     *viewWidthConstraint; 
          

          在Swift中:

          @IBOutlet weak var viewWidthConstraint : NSLayoutConstraint!
          
          1. 更改宽度常量:
          2. 使用以下代码减少常数:

            目标C:

            // Reduce width of view.
            [UIView animateWithDuration:0.35f animations:^{
                self.viewWidthConstraint.constant = 900;
                [self.view layoutIfNeeded];
            }];
            

            Swift 4.0:

            // Reduce width of view.
            UIView.animate(withDuration: 0.35, animations: { () -> Void in
                self.viewWidthConstraint.constant = 900
                self.view.layoutIfNeeded()
            })
            

            同样我们可以将其更改为默认值:

            目标C:

            // Change to default width of view.
            [UIView animateWithDuration:0.35f animations:^{
                self.viewWidthConstraint.constant = 1024;
                [self.view layoutIfNeeded];
            }];
            

            Swift 4.0:

            // Change to the default width of view.
            UIView.animate(withDuration: 0.35, animations: { () -> Void in
                self.viewWidthConstraint.constant = 1024
                self.view.layoutIfNeeded()
            })