I'm trying to figure out a way to understand at which range an instance of UILabel will truncate a text. I know how to get the size that a string would occupy using the -sizeWithFont:constrainedToSize:lineBreakMode:
.
Let's say that we have a UILabel of about 5 lines and a long text, using the method above I'm able to know if it will fit or not. If it doesn't fit I'd like to add another UILabel with the remaining text. I'm doing that because the view layout is mixed with an image and when the image finish I'd like to have a text along the whole width of the view.
I know that with core text I can do that in just one view, but I'd prefer to go easy with UILabel.
/*IMAGE*/##/*TEXT*/
/*IMAGE*/##/*TEXT*/
/*IMAGE*/##/*TEXT*/
/*IMAGE*/##/*TEXT*/
/*IMAGE*/##/*TEXT*/
/*****TEXT*************/
/******TEXT*************/
/******TEXT**************/
Asked
Active
Viewed 2,247 times
2

Andrea
- 26,120
- 10
- 85
- 131
-
I don't think there is built in functionality in iOS that notifies when a Text goes out of bounds inside a UILabel. – rakeshNS Jul 01 '13 at 10:10
1 Answers
2
Well I've found a solution the answer is a duplicate Get truncated text from UILabel
I copy the modified method from that answer, you need to import CoreText framework and be sure that the label is set to word wrap:
- (NSArray *)truncate:(NSString *)text forLabel: (UILabel*) label
{
NSMutableArray *textChunks = [[NSMutableArray alloc] init];
NSString *chunk = [[NSString alloc] init];
NSMutableAttributedString *attrString = nil;
UIFont *uiFont = label.font;
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);
NSDictionary *attr = [NSDictionary dictionaryWithObject:(__bridge id)ctFont forKey:(id)kCTFontAttributeName];
attrString = [[NSMutableAttributedString alloc] initWithString:text attributes:attr];
CTFramesetterRef frameSetter;
CFRange fitRange;
while (attrString.length>0) {
frameSetter = CTFramesetterCreateWithAttributedString ((__bridge CFAttributedStringRef) attrString);
CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0,0), NULL, CGSizeMake(label.bounds.size.width, label.bounds.size.height), &fitRange);
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;
}
-
1FYI the length of the first string in the textChunks array will be the length of the range of the truncated string. – Kevin Jul 22 '14 at 19:01