Ios 如何在objective c中以编程方式添加约束

Ios 如何在objective c中以编程方式添加约束,ios,autolayout,nslayoutconstraint,ios-autolayout,Ios,Autolayout,Nslayoutconstraint,Ios Autolayout,我想以编程方式添加约束,并使用下面的代码添加顶部和左侧约束 NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:label1 attribute:NSLayoutAttributeTop related

我想以编程方式添加约束,并使用下面的代码添加顶部和左侧约束

NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:label1
                                                       attribute:NSLayoutAttributeTop
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:self.view
                                                       attribute:NSLayoutAttributeTop
                                                      multiplier:1
                                                        constant:110];


NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:label1
                                                        attribute:NSLayoutAttributeLeading
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeLeading
                                                       multiplier:1
                                                         constant:10];
标签1
添加到我的视图控制器中。当我在视图中添加这两个约束时

[self.view addConstraint:top];
[self.view addConstraint:left];
它给出控制台中的错误,并且约束不会影响标签

2016-02-09 19:36:59.824 testinMRC[99160:313382] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x7fa5c8738610 V:|-(110)-[UILabel:0x7fa5c8626940'Label']   (Names: '|':UIView:0x7fa5c86267b0 )>",
    "<NSIBPrototypingLayoutConstraint:0x7fa5c8628a70 'IB auto generated at build time for view with fixed frame' V:|-(88)-[UILabel:0x7fa5c8626940'Label']   (Names: '|':UIView:0x7fa5c86267b0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fa5c8738610 V:|-(110)-[UILabel:0x7fa5c8626940'Label']   (Names: '|':UIView:0x7fa5c86267b0 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2016-02-09 19:36:59.889 testinMRC[99160:313382] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x7fa5c87334b0 H:|-(10)-[UILabel:0x7fa5c8626940'Label']   (Names: '|':UIView:0x7fa5c86267b0 )>",
    "<NSIBPrototypingLayoutConstraint:0x7fa5c86285c0 'IB auto generated at build time for view with fixed frame' H:|-(188)-[UILabel:0x7fa5c8626940'Label'](LTR)   (Names: '|':UIView:0x7fa5c86267b0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fa5c87334b0 H:|-(10)-[UILabel:0x7fa5c8626940'Label']   (Names: '|':UIView:0x7fa5c86267b0 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2016-02-09 19:36:59.824 testinMRC[99160:313382]无法同时满足约束。
可能下面列表中至少有一个约束是您不想要的。
试试这个:
(1) 看看每一个约束,试着找出你不期望的;
(2) 找到添加了不需要的约束的代码,然后修复它。
(
"",
""
)
将尝试通过打破约束进行恢复
在UIViewAlertForUnsatifiableConstraints处创建一个符号断点,以便在调试器中捕获该断点。
中列出的UIView上UIConstraintBasedLayoutDebugging类别中的方法也可能会有所帮助。
2016-02-09 19:36:59.889 testinMRC[99160:313382]无法同时满足约束。
可能下面列表中至少有一个约束是您不想要的。
试试这个:
(1) 看看每一个约束,试着找出你不期望的;
(2) 找到添加了不需要的约束的代码,然后修复它。
(
"",
""
)
将尝试通过打破约束进行恢复
在UIViewAlertForUnsatifiableConstraints处创建一个符号断点,以便在调试器中捕获该断点。
中列出的UIView上UIConstraintBasedLayoutDebugging类别中的方法也可能会有所帮助。
有人能告诉我为什么会出现这个错误吗?
请帮助我简短说明解决方案

问题不在于您的代码,而在于构建时自动生成的带固定帧查看的
IB消息:

如果您自己不添加约束,Interface Builder会自动为您生成约束。 你可以通过以下两种方法来避免它

  • 在项目导航器中选择nib或故事板,转到文件检查器并取消选中
    使用自动布局

  • 在Interface Builder中添加一些约束,并将其设置为在生成时删除

在您的案例中,错误明确表示您的视图存在冲突约束。可能是因为您试图将约束添加到已从Interface Builder获得的视图中。即使您没有明确设置任何约束,IB也会在检测到缺少某些约束时为您提供约束

我在您提到的注释中看到,您希望以编程方式执行所有操作。在这种情况下,请看一段代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *view = [UIView new];
    view.backgroundColor = [UIColor redColor];

    [view setTranslatesAutoresizingMaskIntoConstraints:NO];

    [self.view addSubview:view];

    NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:100];
    NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:100];

    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:50];
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:50];

    [self.view addConstraints:@[left, top]];
    [view addConstraints:@[height, width]];

}
这是不言自明的。如您所见,我必须为视图添加宽度和高度约束,因为只有左侧和顶部不能完全描述其位置

结果:

我鼓励您尝试视觉格式语言。同样的结果也可以用更少的代码实现。此代码会导致非常相同的结果:

NSArray *horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"|-100-[view(50)]" options:0 metrics:nil views:@{@"view" : view}];
NSArray *vertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[view(50)]" options:0 metrics:nil views:@{@"view" : view}];

[self.view addConstraints:vertical];
[self.view addConstraints:horizontal];

让我知道这是否有用。干杯。

看起来您的布局约束相互冲突。约束很可能是在情节提要中设置的,您正试图以编程方式添加与之直接冲突的约束

看起来您正在尝试在操作发生后将UIView移到一边。例如,按下一个按钮,将一张笑脸图片从屏幕中间移到左上角

直接在代码中添加和删除约束可能是一个巨大的难题,因为代码膨胀、单元测试和警告充斥着您的控制台

最好在情节提要中创建主UIView,并有一个隐藏的占位符UIView,该占位符保存您希望UIView在按下按钮后具有的所有约束。然后,您可以通过编程方式切换这些UIView的所有约束。因此,要修改的视图将具有占位符的位置、宽度和高度,而占位符将具有要修改的视图的位置和高度

这样,在以编程方式更改布局约束时,您将永远不会出现此错误,因为任何错误都将被情节提要捕获

有一些开源软件可以用一两行代码为您实现这一点。(文档中还有一些youtube视频教程)

安装cocoapod后,您的代码将如下所示

这将是视图控制器中的代码,其中包含要修改的UIView和占位符UIView


第一个选项,取消选中“使用自动布局”
,可能会对项目产生巨大的、全面的影响,并要求OP切换到旧的“struts and springs”样式大小调整。添加缺少的约束并将其标记为“在构建时删除”的第二个选项似乎是一个更好的解决方案。在运行时创建标签时,上述代码是否正确。请使用砌体以编程方式添加约束。此处添加的最新方法:
[view SetTranslatesAutoResizezingMaskinToConstraints:NO]这是一项关键要求。
//UIView* viewBeforeChange
//UIView* hiddenViewAfterChange
[self switchViewConst:viewBeforeChange secondView:hiddenViewAfterChange];