Skip to content

Instantly share code, notes, and snippets.

@MosheBerman
Created October 29, 2012 07:38
Show Gist options
  • Save MosheBerman/3972164 to your computer and use it in GitHub Desktop.
Save MosheBerman/3972164 to your computer and use it in GitHub Desktop.
Return a substring that fits a given rect
//
// NSString+MBDialogString.m
// TileParser
//
// Created by Moshe Berman on 9/23/12.
//
//
#import "NSString+MBDialogString.h"
@implementation NSString (MBDialogString)
- (NSString *) substringThatFitsFrame:(CGRect)frame withFont:(UIFont *)font{
NSString *truncatedString = self;
CGSize size = [truncatedString sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];
NSMutableArray *components = [[truncatedString componentsSeparatedByString:@" "] mutableCopy];
while (frame.size.width <= size.width || frame.size.height <= size.height) {
[components removeLastObject];
truncatedString = [components componentsJoinedByString:@" "];
size = [truncatedString sizeWithFont:font constrainedToSize:frame.size lineBreakMode:NSLineBreakByWordWrapping];
}
return truncatedString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment