Doug Smith
Doug Smith

Reputation: 29316

Why is this constraint not working?

In my table view's cellForRowAtIndexPath: method I have the following code to add an image and align it in the cell:

        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];

However each time the image does indeed get added, but it just sits in the top left corner of the cell. What's wrong with the above code that's causing the constraint not to work?

Upvotes: 0

Views: 2580

Answers (2)

Serhii Yakovenko
Serhii Yakovenko

Reputation: 12654

Your code works for me after setting translatesAutoresizingMaskIntoConstraints to NO:

UIImageView *PocketIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pocket-icon"]];
PocketIcon.translatesAutoresizingMaskIntoConstraints = NO;
[cell addSubview:PocketIcon];

Another little advice I'd like to give. I use constrains extensively and my life became much easier after I started using category for working with constraints, this one:

https://github.com/PureLayout/PureLayout

I suggest you try it too.

Upvotes: 3

BooRanger
BooRanger

Reputation: 1526

So add your imageView and constraints to cell.contentView not cell ( [cell.contentView addSubview:PocketIcon];). Also you want to turn off AutoresizingMask, so add this[PocketIcon setTranslatesAutoresizingMaskIntoConstraints:NO] . You may need a bool to make sure not to add the constraints more then once as the table is scrolled.

Upvotes: 2

Related Questions