我想手动添加约束;每次代码尝试添加centerX和centerY约束时,我都会出现以下错误:
由于未捕获的异常'NSGenericException'而终止应用程序,原因:'无法在视图上安装约束。约束是否引用了视图子树之外的内容?那是违法的。约束:(活动)>视图:>'
我之前检查过多个问题,但没有任何帮助:/
谢谢
码
[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];
删除addConstraint
行并在每次约束实例化后添加.active = YES
。同时更改[image superview]
为cell
尝试将centerX和centerY约束添加到imageView的superview,而不是imageView
[cell.contentView addConstraint:imageViewCenterXConstraint];
[cell.contentView addConstraint:imageViewCenterYConstraint];
请在向UIImageView添加约束后尝试此操作。
对于Objective C
[cell.contentView layoutIfNeeded];
[self.view layoutIfNeeded];
对于斯威夫特
cell.contentView.layoutIfNeeded()
self.view.layoutIfNeeded()
请先尝试一下,先给出约束,然后再将imageView添加到单元格内容中。
你为什么不用:
imageView.center = cell.center
它应该将您的图像置于细胞中心。