为什么这个约束不起作用?

时间:2013-10-17 19:41:49

标签: ios objective-c autolayout nslayoutconstraint

在我的表视图的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];

然而,每次图像确实被添加,但它只是位于单元格的左上角。导致约束不起作用的上述代码出了什么问题?

2 个答案:

答案 0 :(得分:3)

translatesAutoresizingMaskIntoConstraints设置为NO:

后,您的代码适用于我
UIImageView *PocketIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pocket-icon"]];
PocketIcon.translatesAutoresizingMaskIntoConstraints = NO;
[cell addSubview:PocketIcon];

我想给出的另一个小建议。在我开始使用类别来处理约束之后,我广泛使用约束并且我的生活变得更加 了,这个:

https://github.com/PureLayout/PureLayout

我建议你也尝试一下。

答案 1 :(得分:2)

所以将imageView和约束添加到cell.contentView而不是cell([cell.contentView addSubview:PocketIcon];)。您还要关闭AutoresizingMask,因此请添加此[PocketIcon setTranslatesAutoresizingMaskIntoConstraints:NO]。您可能需要一个bool,以确保在滚动表时不再添加约束一次。