Created
June 17, 2016 15:52
-
-
Save simonbromberg/7df893d1e373a4572c12d1f21b90814d to your computer and use it in GitHub Desktop.
This file contains 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
- (NSString *)addSpacesToCharacters:(NSArray *)characters { | |
if (characters.count <= 1) { | |
return characters.firstObject; | |
} | |
// bounding rect of base string, divide by length, calculate optimium number of spaces | |
CGRect boundingRect = CGRectZero; | |
CGSize constraintSize = self.view.frame.size; | |
NSString *string = [characters componentsJoinedByString:@""]; | |
UIFont *drawingFont = self.myLabel.font; | |
NSDictionary *attributes = @{NSFontAttributeName : drawingFont, NSForegroundColorAttributeName : [UIColor blackColor]}; | |
boundingRect = [string boundingRectWithSize:constraintSize options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil]; | |
CGFloat width = boundingRect.size.width; | |
CGFloat characterSize = width / string.length; | |
CGFloat targetSize = self.view.frame.size.width - 20.f; | |
CGFloat difference = targetSize - width; | |
int spacesNeeded = ceilf(difference / characterSize); | |
int numGaps = (int)string.length - 1; | |
int spacesPerGap = spacesNeeded / numGaps; | |
return [characters componentsJoinedByString:[@"" stringByPaddingToLength:spacesPerGap withString:@" " startingAtIndex:0]]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment