kgreenek
kgreenek

Reputation: 5024

UILabel truncate middle lines in multi-line label

I have a UILabel that has 3 lines max. Here is the code:

_testLabel = [[UILabel alloc] init];
_testLabel.text = @"Line 11111111111111\nLine 2\nLine 3";
_testLabel.numberOfLines = 3;
_testLabel.lineBreakMode = NSLineBreakByTruncatingTail;
[_testLabel sizeToFit];
_testLabel.width -= 5;

By calling sizeToFit and then subtracting 5, I cause line 1 to wrap. This in turn pushes line 3 outside of the allowed bounds, so at the end of "Line 2" there is a "..." and line 3 is not shown.

Instead of wrapping line 1 and truncating line 3, what I really want it to truncate line 1. This way, any lines that are too long to fit in the specified width will be truncated and NOT wrapped.

Is there a way to achieve this?

The best I can think of is to split the string at every '\n' char, and have a separate UILabel for each line with numberOfLines set to 1 for each.

EDIT:

To be more clear, here is what the label looks like with the example code above:

Line
11111111111111
Line 2...

And here is what I would like it to look like:

Line 11111111111...
Line 2
Line 3

Upvotes: 3

Views: 2993

Answers (3)

Mina Gerges
Mina Gerges

Reputation: 329

You are doing it right . You need only one other line .

set "adjustsFontSizeToFitWidth" with "false" in order to prevent the label from fitting width by changing font size.

Upvotes: 0

Ricky
Ricky

Reputation: 3171

You probably want to calculate the size of the UILabel before you set its text, then tweak your line break settings.

See NSString's method: - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

Upvotes: 0

Related Questions