I have a two line UILabel. I want its line break mode NSLineBreakByTruncatingMiddle. The problem i am getting is if text is small enough to fit in one line, its showing it in middle of label instead of at top. I am using iOS6 and autolayout so sizeToFit is not working for me. How can i achieve this? I want if text is small to fit one line it should be vertically top aligned. I have tried this, but its truncating and showing the text in one line only rather than two line.
Asked
Active
Viewed 939 times
1 Answers
0
You need to calculate the required size and update the frame of your label:
CGSize s = [myLabelString sizeWithFont:...
constrainedToSize:CGSizeMake(..., MAXFLOAT)
lineBreakMode:NSLineBreakByTruncatingMiddle];
With whatever font your label is using and its width.

Wain
- 118,658
- 15
- 128
- 151
-
your answer if right, but one more thing is that if I took NSAttributedString, its truncating text in only one line though its taking size of two lines. I also tried setting line break mode of NSParagraphStyle in NSAttributedString but did't work. Can you please update on this also? – Bhushan B Jun 28 '13 at 13:15
-
With attributed strings you should get the size with `boundingRectWithSize:options:context:`. – Wain Jun 28 '13 at 13:23
-
Hi wain, i am getting the size using boundingRectWithSize:options:context: but still its truncating attributedString in one line if text is greater than one line. How should i use Label with two lines, NSAttributedString, NSLineBreakByTruncatingMiddle and sizeThatFits? – Bhushan B Jul 04 '13 at 07:33
-
Have you set the number of lines on the label? – Wain Jul 04 '13 at 08:25
-
And you're setting the label size directly now? It could be a border related issue where the label doesn't actually have as much space for rendering the text as its frame may suggest. So you may need to set the frame a little bigger. – Wain Jul 04 '13 at 09:43
-
when i set the NSLineBreakByWordWrapping instead of NSLineBreakByTruncatingMiddle it correctly shows text on two line. So i dont think it is an frame issue. You can check some links http://lists.apple.com/archives/cocoa-dev/2012/Nov/msg00180.html http://lists.apple.com/archives/cocoa-dev/2012/Nov/msg00187.html – Bhushan B Jul 04 '13 at 09:52
-
hmm, does the text happen to be just the length where that last word is the only part that should wrap? I don't have an actual answer now, it sounds a bit like a bug / feature of how the truncation is applied. – Wain Jul 04 '13 at 09:58