Skip to content

Instantly share code, notes, and snippets.

@ericcj
Created August 29, 2013 13:15
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ericcj/6377938 to your computer and use it in GitHub Desktop.
Save ericcj/6377938 to your computer and use it in GitHub Desktop.
crazy that hiding a uiview doesn't affect its autolayout constraints. here's a category for the rest of the world who uses dynamic interfaces
#import <UIKit/UIKit.h>
@interface UIView (TLLayout)
@property (nonatomic, strong) NSArray *hiddenConstraints;
// set hidden and remove any constraints involving this view from its superview
- (void)hideAndRemoveConstraints;
- (void)showAndRestoreConstraints;
@end
#import <objc/runtime.h>
#import "UIView+TLLayout.h"
MAKE_CATEGORIES_LOADABLE(UIView_TLLayout)
static char kTLHiddenConstraintsKey;
@implementation UIView (TLLayout)
@dynamic hiddenConstraints;
- (NSArray *)hiddenConstraints {
return objc_getAssociatedObject(self, &kTLHiddenConstraintsKey);
}
- (void)setHiddenConstraints:(NSArray *)constraints {
objc_setAssociatedObject(self, &kTLHiddenConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)hideAndRemoveConstraints
{
self.hidden = YES;
if (!self.hiddenConstraints) {
self.hiddenConstraints = [self.superview.constraints objectsPassingTest:^BOOL(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
return constraint.firstItem == self || constraint.secondItem == self;
}];
[self.superview removeConstraints:self.hiddenConstraints];
}
}
- (void)showAndRestoreConstraints
{
if (self.hiddenConstraints) {
[self.superview addConstraints:self.hiddenConstraints];
self.hiddenConstraints = nil;
}
self.hidden = NO;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment