在我的 TableView 的 cellForRowAtIndexPath:
方法中,我有以下代码来添加图像并在单元格中对齐它:
UIImageView *PocketIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pocket-icon"]];
[cell addSubview:PocketIcon];
NSLayoutConstraint *iconDistanceFromCellTopConstraint = [NSLayoutConstraint constraintWithItem:PocketIcon attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTop multiplier:1.0 constant:14.0];
[cell addConstraint:iconDistanceFromCellTopConstraint];
NSLayoutConstraint *iconDistanceFromCellLeftConstraint = [NSLayoutConstraint constraintWithItem:PocketIcon attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeLeft multiplier:1.0 constant:22.0];
[cell addConstraint:iconDistanceFromCellLeftConstraint];
然而,每次确实添加了图像,但它只是位于单元格的左上角。导致约束不起作用的上述代码有什么问题?
最佳答案
将 translatesAutoresizingMaskIntoConstraints
设置为 NO 后,您的代码对我有用:
UIImageView *PocketIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pocket-icon"]];
PocketIcon.translatesAutoresizingMaskIntoConstraints = NO;
[cell addSubview:PocketIcon];
我想给的另一个小建议。我广泛使用约束,在我开始使用类别来处理约束后,我的生活变得很多更轻松,这个:
https://github.com/PureLayout/PureLayout
我建议你也试试。
关于ios - 为什么这个约束不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435755/