简体   繁体   English

Xcode约束?

[英]Xcode constraints?

I am trying to understand and work with the constraint feature for Xcode. 我正在尝试了解和使用Xcode的约束功能。 I can see how it can be really useful if you are a few views, since you can really specify how each one should align itself. 我可以看到如果有几个视图,它真的很有用,因为您可以指定每个视图如何对齐。

However, if you have a lot of views this becomes a tedious task, especially if you start messing with them programmatically (like moving them). 但是,如果您有很多视图,这将成为一项繁琐的任务,尤其是当您开始以编程方式将它们弄乱(例如移动它们)时。 For example the below image: 例如下图:

风景

I want it to look like this when i expand and shrink the screen, but alas, it does not. 当我扩大和缩小屏幕时,我希望它看起来像这样,但是,事实并非如此。 Also, since they are constantly aligning to be next to each other, if i move one programmatically (like i'm making a game), the other will unintentionally move with it. 而且,由于它们一直在相互靠近,因此如果我以编程方式移动一个(例如我正在制作游戏),则另一个会无意间随之移动。

So basically, how on earth am i supposed to work with constraints when featuring quite a bit of view objects on screen + moving them in the code? 因此,基本上,当在屏幕上显示大量视图对象并在代码中移动它们时,我应该如何处理约束? Any tips are greatly appreciated! 任何提示,不胜感激! (and yes, i have tried adding / removing constraints for every single view one at a time, and firstly, it's a tedious task, and secondly, it keeps adding constraints for the views to align them with each other, and you rarely want that in a game where you move them). (是的,我尝试一次为每个单个视图添加/删除约束,首先,这是一个繁琐的任务,其次,它不断为视图添加约束以使它们彼此对齐,而您很少想要在移动它们的游戏中)。

thanks on advance! 提前谢谢!

You could try to update the constraints instead of removing and adding them all the time. 您可以尝试更新约束,而不是一直删除和添加约束。 You can create IBOutlets for all the constraints you need to change and then you can update them by changing the constant value 您可以为需要更改的所有约束创建IBOutlets ,然后可以通过更改constant量值来更新它们

[self.heightConstraint setConstant:newValue];

Then you need to call [self layoutIfNeeded] , probably in an animation block, to see the changes after updating the constraints: 然后,您可能需要在动画块中调用[self layoutIfNeeded] ,以在更新约束后查看更改:

[UIView animateWithDuration:0.5 animations:^{
    [self layoutIfNeeded];
}];

I don't really know the details of your application, but maybe if you think about the constraints from the perspective of how the views relate to each other, maybe moving them would not be so difficult. 我并不真正了解您的应用程序的细节,但是也许如果您从视图之间如何关联的角度考虑约束,那么移动它们就不会那么困难。

Another idea would be to group the views together in an UIView subclass. 另一个想法是将视图归为一个UIView子类。 Maybe something like RowView that has the 3 images and handles the constraints just for those. 也许像RowView这样的东西具有3张图像并处理这些图像的约束。

What I mean is something like "Divide and Conquer", not handling all the constraints in one view, but group them together, in a way that makes sense for you application. 我的意思是像“分而治之”之类的东西,不是在一个视图中处理所有约束,而是以对您的应用程序有意义的方式将它们组合在一起。

Hope this helps! 希望这可以帮助! Good luck with your project. 祝您项目顺利。

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

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