I have custom subclass of a UITableViewCell with some constraints set.
Problem is when I try to change size of one view like this:
CGRect frm = CGRectMake(0, 0, someValue, 30);
cell.indentView.frame = frm;
other views, which depend on cell.indentView width, are not moving at all.
What can be the case?
This code will work:
// enumerate over all constraints
for (NSLayoutConstraint *constraint in cell.indentView.constraints) {
// find constraint on this view and with 'width' attribute
if (constraint.firstItem == cell.indentView && constraint.firstAttribute == NSLayoutAttributeWidth)
{
// increase width of constraint
constraint.constant = someValue;
break;
}
}
It’s because you cannot just change the frame of an object that has autolayout constraints (because constraints dictate the locations, not manually set
frameproperties … theframeproperties will be reset as constraints are reapplied). See this loosely related post in which it is demonstrated how to properly adjust a constraint to move a view. (In that case, we’re animating, which is not the issue here, but it does demonstrate how how one adjusts a constraint to effect the movement of aUIView.)In short, if you want to move a
UIViewwithin autolayout, you must not try to change theframe, but rather adjust the constraints themselves. This is simplified if you createIBOutletreferences for the constraints themselves, at which point, you can adjust theconstantof theNSLayoutConstraint.Update:
Egor recommended enumerating the constraints and editing the one that matched the one in question. That works great, but personally, I prefer to have an
IBOutletfor the specific constraint I want to edit rather than enumerating them and hunting the one in question. If you had anIBOutletcalledindentViewWidthConstraintfor the widthNSLayoutConstraintof theindentView, you could then simply: