UILabel does not work correctly after changing text

advertisements

I'm working via the IB and have a UILabel that's stretched almost to the end of the layout. I have it set with Lines=2, because the max amount of lines it should take is 2. However if it's only 1 line long, I would like it to have a vertical justification of top.

Label settings in IB:

 Lines:2
 Line breaks: Word wrap

In code, in the viewDidLoad method I set the text of the UILabel. However as part of the functionality at a point the text must change. This is my code:

[_main_lbl1 setText:[myUI MAIN_TITLE]];  //Always only 1 line
[_main_lblsub1 setText:[myUI SUB_TITLE]]; //May be 1 or 2 lines
[_main_lblsub1 sizeToFit];  //Causes vertical alignment (I believe)

Whenever I change the text and rerun sizeToFit, the text wrapping becomes totally messed up. Instead of reaching almost the end of the UILabel as set up in the IB, in some cases the text will wrap at little more than half the distance, in some cases it doesn't wrap at all.

Image of layout in IB:

Image of resulting label in simulator:

In the first label it seems to be working ok, the second label doesn't wrap at all.

Is there anything I have to do to keep the text wrapping when changing the UILabel text? Anything else I'm missing?

Note: Updated question to include more detail and pics.

Thanks


You shouldn't have to do anything special. It will automatically wrap the text to fit when you change it. Otherwise the text would run out of the text labels bounds (which is not what you want). Your problem is that sizeToFit permanently changes the frame of the label. It makes it as small as possible while still showing the text. You are having it resize its frame to the original text and then you are changing the text so it is no longer sized properly. You should reset the frame back to it's original, change the text, and finally call size to fit again.

In viewDidLoad:

self.originalFrame =  self.mainLabelSub1.frame;

Then in viewWillAppear:

self.mainLabel1.frame = self.originalFrame;
self.mainLabel1.text = @"New Text";

Note: A good way to see the borders of the text label to get an idea for the wrapping potential is to temporary set the background of the label to something like magentaColor that stands out.