我正在尝试手动添加约束;每次代码尝试添加centerX和centerY约束时,我都会出现以下错误:
由于未捕获的异常终止应用程序' NSGenericException', 原因:'无法在视图上安装约束。是约束 引用视图子树外的东西?那' S 非法。约束: (有源)>视图产品:>'
我之前检查过多个问题,但没有任何帮助:/
谢谢
CODE
[cell.contentView addSubview:imageView];
[cell.contentView addSubview:title];
title.translatesAutoresizingMaskIntoConstraints = NO;
imageView.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *imageViewHeightConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:[UIScreen mainScreen].bounds.size.width/8];
NSLayoutConstraint *imageViewWidthtConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:imageView
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0];
NSLayoutConstraint *imageViewCenterXConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:[imageView superview]
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
NSLayoutConstraint *imageViewCenterYConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:[imageView superview]
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[imageView addConstraint:imageViewHeightConstraint];
[imageView addConstraint:imageViewWidthtConstraint];
[imageView addConstraint:imageViewCenterXConstraint];
[imageView addConstraint:imageViewCenterYConstraint];
答案 0 :(得分:1)
删除addConstraint
行并在每次约束实例化后添加.active = YES
。同时更改[image superview]
cell
答案 1 :(得分:0)
尝试将centerX和centerY约束添加到imageView的superview,而不是imageView
[cell.contentView addConstraint:imageViewCenterXConstraint];
[cell.contentView addConstraint:imageViewCenterYConstraint];
答案 2 :(得分:0)
请在向UIImageView添加约束后尝试此操作。
对于目标C
[cell.contentView layoutIfNeeded];
[self.view layoutIfNeeded];
对于Swift
cell.contentView.layoutIfNeeded()
self.view.layoutIfNeeded()
请先尝试一下,先给出约束,然后再将imageView添加到单元格内容中。
答案 3 :(得分:-2)
为什么不使用:
imageView.center = cell.center
它应该将您的图像置于细胞中心。