The function you are looking for is CTFramesetterSuggestFrameSizeWithConstraints . In essence, this allows you to find out the number of characters that correspond to a specific frame. You can use this number to turn off the current text and insert a button.
I wrote an implementation of this function for a subclass of UILabel:
- (NSInteger)numberOfCharactersThatFitLabel { // Create an 'CTFramesetterRef' from an attributed string CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL); NSDictionary *attributes = [NSDictionary dictionaryWithObject:(__bridge id)fontRef forKey:(id)kCTFontAttributeName]; CFRelease(fontRef); NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.text attributes:attributes]; CTFramesetterRef frameSetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString); // Get a suggested character count that would fit the attributed string CFRange characterFitRange; CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0,0), NULL, CGSizeMake(self.bounds.size.width, self.numberOfLines*self.font.lineHeight), &characterFitRange); CFRelease(frameSetterRef); return (NSInteger)characterFitRange.length; }
Here is a bug post for the full implementation of cutting off random text to a specified number of lines and adding the text “see more” to it.
kgaidis
source share