Skip to content

Instantly share code, notes, and snippets.

@aceontech
Created February 3, 2015 16:14
Show Gist options
  • Save aceontech/bc799784b0a7c24cbd28 to your computer and use it in GitHub Desktop.
Save aceontech/bc799784b0a7c24cbd28 to your computer and use it in GitHub Desktop.
Category on UILabel for easily sizing a label to fit in a given width.
//
// Created by Alex Manarpies on 03/02/15.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UILabel (AOTSizingUtilities)
- (void)aot_sizeToFitInWidth:(CGFloat)width;
- (void)aot_sizeToFitInWidth:(CGFloat)width inPlace:(BOOL)inPlace;
@end
//
// Created by Alex Manarpies on 03/02/15.
//
#import "UILabel+AOTSizingUtilities.h"
@implementation UILabel (AOTSizingUtilities)
- (void)aot_sizeToFitInWidth:(CGFloat)width inPlace:(BOOL)inPlace {
CGPoint originalOrigin = inPlace ? self.frame.origin : CGPointZero;
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
CGRect frame = [self.text boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName : self.font}
context:nil];
frame.origin = originalOrigin;
self.frame = CGRectIntegral(frame);
}
- (void)aot_sizeToFitInWidth:(CGFloat)width {
[self aot_sizeToFitInWidth:width inPlace:YES];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment