Skip to content

Instantly share code, notes, and snippets.

@bgulanowski
Created December 11, 2014 13:57
Show Gist options
  • Save bgulanowski/63be216ef1cd9f5b804e to your computer and use it in GitHub Desktop.
Save bgulanowski/63be216ef1cd9f5b804e to your computer and use it in GitHub Desktop.
Swap a subview with another view, copying the constraints from the first to the second.
@implementation UIView (SubviewReplacing)
- (void)replaceSubview:(UIView *)subview withView:(UIView *)newView
{
newView.frame = subview.frame;
[self addSubview:newView];
for (NSLayoutConstraint *constraint in [subview.constraints arrayByAddingObjectsFromArray:self.constraints]) {
id firstItem = nil;
id secondItem = nil;
if (constraint.firstItem == subview) {
firstItem = newView;
secondItem = constraint.secondItem;
}
else if (constraint.secondItem == subview) {
firstItem = constraint.firstItem;
secondItem = newView;
}
if (firstItem) {
NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:firstItem attribute:constraint.firstAttribute relatedBy:constraint.relation toItem:secondItem attribute:constraint.secondAttribute multiplier:constraint.multiplier constant:constraint.constant];
if (nil == secondItem) {
[self addConstraint:newConstraint];
}
else {
[newView addConstraint:newConstraint];
}
}
}
[subview removeFromSuperview];
subview = newView;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment