0

I have a very very long text, so instead of using UITextView, I want to truncate the text to small chunks that can fit to a label with width and height 300, 400, and based on number of chunks, I want to create UILabel dynamically and populate them with these chunks.

I have written a method but it seems doesn't return the actual strings that can fit. it returns shorter strings.

am I missing something? is there anyway I can do this?

- (NSArray *)truncate:(NSString *)text
{
    NSMutableArray *textChunks = [[NSMutableArray alloc] init];

    NSString *chunk = [[NSString alloc] init];

    CTFramesetterRef frameSetter;
    UIFont *uiFont = [UIFont systemFontOfSize:17.0f];
    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);
    NSDictionary *attr = [NSDictionary dictionaryWithObject:(__bridge id)ctFont forKey:(id)kCTFontAttributeName];
    NSMutableAttributedString *attrString  = [[NSMutableAttributedString alloc] initWithString:text attributes:attr];

    CFRange fitRange;
    while (attrString.length>0) {

        frameSetter = CTFramesetterCreateWithAttributedString ((__bridge CFAttributedStringRef) attrString);
           CGSize framSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0,0), NULL, CGSizeMake(myLabel.frame.size.width, myLabel.frame.size.height), &fitRange);
        NSLog(@"height: %f", framSize.height);
        CFRelease(frameSetter);

       chunk = [[attrString attributedSubstringFromRange:NSMakeRange(0, fitRange.length)] string];

        [textChunks addObject:chunk];

        [attrString setAttributedString: [attrString attributedSubstringFromRange:NSMakeRange(fitRange.length, attrString.string.length-fitRange.length)]];

    }


    return textChunks;
}
Hashem Aboonajmi
  • 13,077
  • 8
  • 66
  • 75

1 Answers1

0

Yes, you need to add a paragraph style in order to get the width/height measure to work properly. See giving-framesetter-the-correct-line-spacing-adjustment. Note how CTFontGetLeading() is used to get the font leading and then this property is set vai CFAttributedStringSetAttributes().

Community
  • 1
  • 1
MoDJ
  • 4,309
  • 2
  • 30
  • 65