Skip to content

Instantly share code, notes, and snippets.

@safareli
Created November 2, 2014 11:58
Show Gist options
  • Save safareli/a3866d8486795bec5e11 to your computer and use it in GitHub Desktop.
Save safareli/a3866d8486795bec5e11 to your computer and use it in GitHub Desktop.
UILabel fix for autoresizing http://stackoverflow.com/q/24510596
#import "UILabel+AutoResizeingFix.h"
#import <objc/runtime.h>
@implementation UILabel (AutoResizeingFix)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(setFrame:);
SEL swizzledSelector = @selector(fix_setFrame:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
originalSelector = @selector(intrinsicContentSize);
swizzledSelector = @selector(fix_intrinsicContentSize);
originalMethod = class_getInstanceMethod(class, originalSelector);
swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
#pragma mark - Method Swizzling
-(void)fix_setFrame:(CGRect)frame{
[self fix_setFrame:frame];
if (self.numberOfLines == 0) {
// If this is a multiline label, need to make sure
// `preferredMaxLayoutWidth`always matches the frame width
// (i.e. orientation change can mess this up)
if (self.preferredMaxLayoutWidth != frame.size.width) {
self.preferredMaxLayoutWidth = frame.size.width;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize)fix_intrinsicContentSize{
CGSize size = [self fix_intrinsicContentSize];
if (self.numberOfLines == 0) {
// There's a bug where intrinsic content size
// may be 1 point too short
size.height += 1;
}
return size;
}
@end
#import <UIKit/UIKit.h>
@interface UILabel (AutoResizeingFix)
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment