Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created July 18, 2013 15:07
Show Gist options
  • Save lukeredpath/6030085 to your computer and use it in GitHub Desktop.
Save lukeredpath/6030085 to your computer and use it in GitHub Desktop.
Replaces constraints created in a XIB/Storyboard on a UITableViewCell that relate subviews of the contentView with the cell itself, with ones that relate the subviews with the contentView, as it should be. This bug is fixed in Xcode 5 DP3, apparently.
@interface UITableViewCell (FixConstraints)
/* Finds any constraints that relate between a subview of the cell's content
* view and the cell itself, and replaces them with otherwise identical constraints
* that replace the cell with the content view.
*
* This works around a bug in Interface Builder where subviews added to a content
* view have their constraints related to the cell itself and not the content view,
* which can cause problems if you need to move the content view in any way (e.g.
* swipe to delete).
*/
- (void)realignConstraintsBetweenContentViewSubviewsAndCellWithContentView;
@end
//
// UITableViewCell+FixConstraints.m
// CAN
//
// Created by Luke Redpath on 18/07/2013.
// Copyright (c) 2013 LShift. All rights reserved.
//
#import "UITableViewCell+FixConstraints.h"
@implementation UITableViewCell (FixConstraints)
- (void)realignConstraintsBetweenContentViewSubviewsAndCellWithContentView
{
NSMutableArray *affectedConstraints = [NSMutableArray array];
for (NSLayoutConstraint *constraint in self.constraints) {
// ignore any auto-resizing mask translation constraints
if (![constraint isKindOfClass:[NSLayoutConstraint class]]) continue;
id firstItem, secondItem;
/* If the first/second item is the cell itself, and the other item is a subview of the content
* view, then we want the replacement constraint to point at the content view instead.
*/
if (constraint.firstItem == self && [constraint.secondItem isDescendantOfView:self.contentView]) {
firstItem = self.contentView;
secondItem = constraint.secondItem;
}
else if (constraint.secondItem == self && [constraint.firstItem isDescendantOfView:self.contentView]) {
firstItem = constraint.firstItem;
secondItem = self.contentView;
}
else {
continue;
}
NSLayoutConstraint *replacementConstraint = [NSLayoutConstraint constraintWithItem:firstItem attribute:constraint.firstAttribute relatedBy:constraint.relation toItem:secondItem attribute:constraint.secondAttribute multiplier:constraint.multiplier constant:constraint.constant];
replacementConstraint.priority = constraint.priority;
[self addConstraint:replacementConstraint];
[affectedConstraints addObject:constraint];
}
[self removeConstraints:affectedConstraints];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment