Created
December 11, 2014 13:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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