xcode 删除 NSLayoutConstraint 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30102086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to delete a NSLayoutConstraint
提问by Antoine
In my apps I'm working a lot with constraints, in most cases with animations as well. In certain circumstances I need to remove constraints and add new ones.
在我的应用程序中,我经常使用约束,在大多数情况下也使用动画。在某些情况下,我需要删除约束并添加新的约束。
As I need to support iOS 7 as well, I'm not able to use the active
property, which would else be the solution for me.
由于我还需要支持 iOS 7,因此我无法使用该active
属性,否则这将是我的解决方案。
The way to remove constraints is to use the removeConstraint
method on a UIView
.
去除约束的removeConstraint
方法是使用 a 上的方法UIView
。
Is it possible to create a method like
是否可以创建类似的方法
constraint.remove()
so you don't have to know which view is taking care over the constraint?
所以你不必知道哪个视图正在处理约束?
采纳答案by Antoine
I've ended up using the method autoRemove
provided by the PureLayout
library: https://github.com/smileyborg/PureLayout
我最终使用autoRemove
了PureLayout
图书馆提供的方法:https: //github.com/smileyborg/PureLayout
This method finds the commonSuperview using the firstItem or secondItem and removes the constraint from the correct view.
此方法使用 firstItem 或 secondItem 查找 commonSuperview 并从正确的视图中删除约束。
It resulted in this one liner:
这导致了这个班轮:
containerTopConstraint.autoRemove()
回答by Rory McKinnel
What I do is create arrays of the constraints that I wish to be able to add/remove and simply use the following:
我所做的是创建我希望能够添加/删除的约束数组,并简单地使用以下内容:
@property NSMutableArray *newConstraints;
Fill up the newConstraints
填写 newConstraints
iOS7 and iOS8:
iOS7 和 iOS8:
[self.viewToChange addConstraints:self.newConstraints];
[self.viewToChange removeConstraints:self.newConstraints];
or iOS8 only, use the new mechanism
或仅限 iOS8,使用新机制
[NSLayoutConstraint activateConstraints:self.newConstraints];
[NSLayoutConstraint deactivateConstraints:self.newConstraints];
With this you can apply a set, remove the set and apply a new set.
有了这个,您可以应用一个集合,删除该集合并应用一个新集合。
You can also create the initial list from the storyboard set if you can identify which constraints are which.
如果您可以确定哪些约束是哪些,您还可以从故事板集创建初始列表。
回答by dasdom
No, not that I'm aware of. The automatic managing of the host view only came in iOS8.
不,我不知道。主机视图的自动管理仅在 iOS8 中出现。
An ugly implementation could loop over all constraints of all views to finde the view where it is on.
一个丑陋的实现可能会遍历所有视图的所有约束以找到它所在的视图。
But normally it shouldn't be to hard to manage the constrains in a way that you always know on which view they are defined.
但通常情况下,以一种您始终知道约束是在哪个视图上定义的方式来管理约束应该不难。