Skip to content

Instantly share code, notes, and snippets.

@phamquy
Last active December 15, 2015 04:31
Show Gist options
  • Save phamquy/cf1691b4126206ff5898 to your computer and use it in GitHub Desktop.
Save phamquy/cf1691b4126206ff5898 to your computer and use it in GitHub Desktop.
//------------------------------------------------------------------------------
//
// kLineCount is number of line in truncated mode
-(NSString *)thumbnailString:(NSString*)string {
NSInteger lenght = [string length];
NSString *showMoreString = @"see more";
UIFont* displayFont = <your font>;
CGFloat hOf4Line = (font.lineHeight * kLineCount);
for (NSInteger i = lenght;i >= 0; --i)
{
NSString *resultString = [string substringWithRange:NSMakeRange(0, i)];
resultString = [resultString stringByAppendingFormat:@".....%@",showMoreString];
CGFloat textW = [self targetTextW];
textW = textW - self.descriptionLeftMargin.constant - self.descriptionRighttMargin.constant;
NSLog(@"Width: %@", @(self.tvDescription.frame.size.width));
CGSize size = [resultString sizeForFont:font constraintSize:(CGSize){textW, 99999}];
if (size.height <= hOf4Line) {
return resultString;
}
}
return nil;
}
/// .......
/// In NSString category
- (CGSize) sizeForFont: (UIFont*) font constraintSize: (CGSize) size
{
CGSize reSize;
NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = 0.5;
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject: font forKey: NSFontAttributeName];
CGRect bound = [self boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:stringAttributes context:nil];
reSize = bound.size;
return reSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment