繁体   English   中英

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

[英]How to Programatically Change Position of UIViews When Autolayout is On

我已经在这个问题上停留了很长时间了。 在Objective-c中开发iOS应用程序时,如何在启用自动布局后以编程方式更改UIView的位置(位置)? 不用Autolayout是如此简单,因为我们只为UIView指定了一个新的中心,如下所示:

UIView.center = CGPointMake(x,y);

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

_loginTextLabel.center = CGPointMake(1,1);

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

} completion:nil
 ];
}

实际上,您可以在没有自动布局的情况下在- (void)viewDidLayoutSubviews (或- (void)layoutSubviews如果它位于自定义视图中)中布局_loginTextLabel,则可以像以前一样对视图进行动画处理,而无需进行任何麻烦。

如果使用Nib的自动布局来布局视图,则可以按照Abhishek的说明创建约束的出口,基本上是这样的:

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

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

基本上就像您从笔尖上所做的一样,不同之处在于您只需在动画块中更改约束

[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
}];

为了以编程方式处理Autolayouts,您需要创建Constraint的IBOutlet,它们是NSLayoutConstraints类的,并且要在其中更改位置或框架的位置需要在视图上调用updateConstraintsIfNeeded。然后需要设置浮点值出口的Constant属性。

_constraintHeight.constant = 200;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM