Skip to content

Instantly share code, notes, and snippets.

@zkwentz
Created April 8, 2014 04:54
Show Gist options
  • Save zkwentz/10092364 to your computer and use it in GitHub Desktop.
Save zkwentz/10092364 to your computer and use it in GitHub Desktop.
UILabel+DDSize
//
// UILabel+DDSize.h
//
// Created by Zachary Wentz on 4/7/14.
// @wentz__
#import <UIKit/UIKit.h>
@interface UILabel (DDSize)
- (void)sizeToFitWithScale;
@end
//
// UILabel+DDSize.m
//
// Created by Zachary Wentz on 4/7/14.
// @wentz__
#import "UILabel+DDSize.h"
@implementation UILabel (DDSize)
// Scales font to fit label's rectangle, while taking into account set minimumScaleFactor.
//
// Useful for when you have setup a UILabel in storyboard, and want the text to align to
// the top, but don't want the font to go passed your defined frame's bounds.
- (void)sizeToFitWithScale
{
CGRect origFrame = self.frame;
CGFloat minimumFontSize = self.font.pointSize * self.minimumScaleFactor;
[self sizeToFit];
CGRect newFrame = self.frame;
do {
CGFloat newFontSize = self.font.pointSize - 1;
if (newFontSize < minimumFontSize)
break;
self.font = [UIFont fontWithName:self.font.fontName size:newFontSize];
self.frame = origFrame;
[self sizeToFit];
newFrame = self.frame;
} while (origFrame.size.height < newFrame.size.height);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment