我有一个工具栏,上面有一个我以编程方式添加的UIImageView
。当我尝试将NSConstraint
添加到UIImageView
以使其在工具栏视图中居中时。当我在模拟器上运行它时,它崩溃了。这是我的代码:
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,
nav.frame.size.width, nav.frame.size.height)];
image.image = [UIImage imageNamed:[imageTop objectAtIndex:2]];
[imageToolbar addSubview:image];
[imageToolbar addConstraint:[NSLayoutConstraint constraintWithItem:image
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:imageToolbar
attribute:NSLayoutAttributeCenterX
multiplier:1.0 constant:0]];
[imageToolbar addConstraint:[NSLayoutConstraint constraintWithItem:image
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:imageToolbar
attribute:NSLayoutAttributeCenterY
multiplier:1.0 constant:0]];
错误:
无法同时满足约束。
可能以下列表中的约束中至少有一个是你不需要的约束。试试这个:
(1)查看每个约束,并尝试找出您意想不到的约束;
(2) 找到添加不需要的约束的代码并修复它。(注意:如果您看到不理解NSAutoresizingMaskLayoutConstraints
,请参阅 UIView
属性的文档translatesAutoresizingMaskIntoConstraints
)
(
"<NSLayoutConstraint:0x7fcfc2536f50 UIImageView:0x7fcfc2536d50.centerX == UIToolbar:0x7fcfc2525610.centerX>",
"<NSLayoutConstraint:0x7fcfc252dad0 UIView:0x7fcfc252c750.trailingMargin == UIToolbar:0x7fcfc2525610.trailing - 16>",
"<NSLayoutConstraint:0x7fcfc252db20 UIToolbar:0x7fcfc2525610.leading == UIView:0x7fcfc252c750.leadingMargin - 16>",
"<NSAutoresizingMaskLayoutConstraint:0x7fcfc254fea0 h=--& v=--& UIImageView:0x7fcfc2536d50.midX == + 160>",
"<NSLayoutConstraint:0x7fcfc2551110 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7fcfc252c750(375)]>"
)
将尝试通过打破约束进行恢复
<NSLayoutConstraint:0x7fcfc2536f50 UIImageView:0x7fcfc2536d50.centerX == UIToolbar:0x7fcfc2525610.centerX>
在UIViewAlertForUnsatisfiableConstraints
处创建一个符号断点,以便在调试器中捕获此断点。
UIView 上列出的 UIConstraintBasedLayoutDebugging 类别中的方法也可能有所帮助。
谢谢。
您已创建 UIImageView,但尚未将该图像视图添加到界面。不能为不在界面中的视图添加约束。如果你这样做,你会,呃,崩溃。
此外,您忽略了将translatesAutoresizingMaskIntoConstraints
设置为 NO。如果你忽略了这一点,那么当你添加自己的约束时,你就会遇到约束冲突,你会,呃,崩溃。
实际上,只需在控制台中阅读错误消息即可。正如我的老民间舞蹈老师常说的那样,"音乐告诉你该怎么做!