-
-
Save GeekTree0101/d329250eaf97d8ca29a871dc7c31b1ec 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
This file contains hidden or 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
#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 |
This file contains hidden or 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
#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