Ulas Sancak Ulas Sancak - 1 year ago 176
Objective-C Question

UICollectionViewCell Auto Layout Programmatically

I am trying to create a

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

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

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!

Answer Source

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.