Search code examples
ioscocoauiviewautolayout

Create view with width equal to the table view separator width


I am creating a table view cell that I fill with a custom view. I would like the view width to be the same as the separator inset of the table view (as do text cell look like by default). My code looks like that:

- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
    self.preservesSuperviewLayoutMargins = true;
    self.contentView.preservesSuperviewLayoutMargins = true;

    myInnerView = [[MyInnerView alloc] initWithFrame:CGRectZero];

    [self.contentView addConstraint:[NSLayoutConstraint 
    constraintWithItem:myInnerView 
    attribute:NSLayoutAttributeCenterX
    relatedBy:NSLayoutRelationEqual
    toItem:self.contentView
    attribute:NSLayoutAttributeCenter:
    multiplier:1.0f constant:0.f]];

    [self.contentView addConstraint:[NSLayoutConstraint 
    constraintWithItem:myInnerView
    attribute:NSLayoutAttributeWidth
    relatedBy:NSLayoutRelationEqual
    toItem:self.contentView
    attribute:NSLayoutAttributeWidth
    multiplier:1.0f constant:0.f]];

    // some vertical constraints here
    }
return self;
};        

But this gives me a view that fills exactly the whole screen, not only the inner part. Does anyone know how to solve this ?


Solution

  • The separator is positioned based on readableLayoutGuide.

    Instead go laying out relative to centerX and width, you want to layout relative to the readableLayoutGuide leading and readableLayoutGuide trailing.