如何在自动布局打开时以编程方式更改 UIView 的位置

How to Programatically Change Position of UIViews When Autolayout is On

我已经被这个问题困扰了很长一段时间。在 objective-c 中开发 iOS 应用程序时,我们如何在启用自动布局时以编程方式更改 UIView 的位置(位置)?没有 Autolayout 很容易,因为我们只需为 UIView 指定一个新的中心:

UIView.center = CGPointMake(x,y);

但是,由于自动布局,上述内容不再有效。最终,我试图通过使用从左到右的平移变换来为某个 UIView 设置动画。但是,为了做到这一点,我需要以编程方式移动 UIViews,我目前无法做到这一点。下面是我基本上想做的事情(但由于自动布局而不起作用):

_loginTextLabel.center = CGPointMake(1,1);

[UIView animateWithDuration:0.5 delay:0.5 options:nil animations:^{
    _loginTextLabel.center= CGPointMake(5, 1);

} completion:nil
 ];
}

为了以编程方式处理自动布局,您需要创建约束的 IBOutlets,它们属于 class NSLayoutConstraints,并且您想要更改位置或框架的位置需要调用 updateConstraintsIfNeeded on your view.Then 你需要为你的插座的常量 属性 设置一个浮点值。

_constraintHeight.constant = 200;

实际上,您可以在 - (void)viewDidLayoutSubviews(或 - (void)layoutSubviews,如果它在您的自定义视图中)布局您的 _loginTextLabel 而无需自动布局,然后您可以像以前一样为您的视图设置动画而无需任何麻烦。

如果您使用 Nib 的自动布局来布局视图,那么您可以像 Abhishek 所说的那样创建约束的出口,基本上是这样的:

[self.view layoutIfNeeded];
yourConstraint.constant = whateverYouWant;
[UIView animateWithDuration:1.0 animations:^{ 
   [containerView layoutIfNeeded]; }
];

或者,如果您按照 apple 的建议以编程方式创建约束:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutolayoutPG.pdf

这基本上就像您从 Nib 所做的那样,区别在于您只是在动画块中更改约束

[containerView layoutIfNeeded]; 
[UIView animateWithDuration:1.0 animations:^{
// Make all constraint changes here
[containerView layoutIfNeeded]; // Forces the layout of the subtree animation
block and then captures all of the frame changes
}];