Ulaş Sancak
Ulaş Sancak

Reputation: 907

UICollectionViewCell Auto Layout Programmatically

I am trying to create a UICollectionViewCell subclass with programmatically. I am trying to create with auto layout support.

I want to a UIView to the content view of the cell with adding leading, top, trailing and bottom constraints. But When I do that, My UIView's width and height stays zero. Here is my code inside initWithFrame method:

    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    _someView = [[UIView alloc] initWithFrame:CGRectZero];
    _someView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:_someView];
    NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-2-[someView]-2-|" options:0 metrics:nil views:@{@"someView" : _someView}];
    NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-2-[someView]-2-|" options:0 metrics:nil views:@{@"someView" : _someView}];

    [self.contentView addConstraints:horizontalConstraints];
    [self.contentView addConstraints:verticalConstraints];

And here is the UI debugger's screenshot: enter image description here

Why are these constraints are greyed out?

Thank you!

Upvotes: 1

Views: 2229

Answers (1)

Warren Burton
Warren Burton

Reputation: 17378

The contentView is owned by the UICollectionViewCell so the action of doing this

self.contentView.translatesAutoresizingMaskIntoConstraints = NO;

breaks the layout in the cell.

Its perfectly reasonable to do this for any subviews you own and add to the content view but messing with views you don't own runs the risk of breaking the layout.

Upvotes: 8

Related Questions