I put an CustomView
in UITableViewCell.contentView
, setting the autoresize mask
of the custom view as W+H
.
But when running, the CustomView
gets a larger height than the ContentView
, the ContentView
is 60pt
in height(which is the same as setting in UITableViewDelegate
), but the CustomView
inside contentView
is 76pt
in height.
By Xcode6's view debugging
, I see some strange constraints on my custom view, they are:
self.height = superview.height + 16
self.midY = superview.midY + 8
Where are these constraints come from and how to modify them? I've never set anything with a value 8 or 16.
UPDATE:
I've made a test project, which is simply a tableview in storyboard with a CustomView
loaded from a nib file, and this test project replicated the problem, when running, the CustomView
which is a subview of TableViewCell.contentView
becomes larger in height than the TableViewCell.contentView
.
The test project is here:
https://drive.google.com/file/d/0B5y_NrRbhGlSb1dlbVZNb19vNjQ/view?usp=sharing
At last I understand, auto layout can only form relations in the same xib or storyboard, my CustomView is in a separated xib and is loaded at runtime, so the super view and CustomView don't have any auto layout constraints between them.
If I set translatesAutoresizingMaskIntoConstraints
to YES, then there goes the problem, I still don't know why using W+H as auto resizing mask makes CustomView taller than its super view(cell.contentView), but I found a way around:
I manually add constraints between superview and CustomView, and turn off customView. translatesAutoresizingMaskIntoConstraints
, there the code goes:
customView.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:customView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1 constant:0];
NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:customView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:customView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:customView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeRight multiplier:1 constant:0];
[cell.contentView addConstraints:@[top, bottom, left, right]];