Reputation: 1667
I am trying to build up an custom table view.
As you can see in the picture, I set the width of the label by default as 160 point in side the story board and change the width on the fly when the table is loaded. I am implementing this by modifying "cellForRowAtIndexPath" delegate method.
So based on the length of the date, I am setting the width of Label1 to maximum utilise the real estate on the phone screen.
CGFloat timeStampWidth = [cell.timestamp.text sizeWithFont:cell.timestamp.font].width;
CGFloat ksCompanyNameLableMaxWidth = 235;
NSLog(@"timeStampWidth:%f", timeStampWidth);
CGSize companyNameLableSize = CGSizeMake((ksCompanyNameLableMaxWidth - timeStampWidth), cell.companyNameLabel.frame.size.height);
CGRect newFrame = cell.companyNameLabel.frame;
newFrame.size = companyNameLableSize;
cell.companyNameLabel.frame = newFrame;
But when I load the app, all the label1s are set as 160 point as set in the storyboard although by debugging I have seen my code get executed for each cell.
To my surprise, if I scroll down and scroll back up again. The block of code is getting called again and the label is set as I wish.
Moreover, if I switch between the tabs, the label is restored to the abnormal status again.
Upvotes: 2
Views: 6740
Reputation: 3120
You can also create and position the UILabel programatically, this way the iOS auto-layout will not interfere with your frame change.
Upvotes: 0
Reputation: 672
If you are using auto layout, you can just set the x and y position, and then nothing for the height and width, and the label will correctly size itself to fit its contents. One caveat if you are using Xibs or Storyboards, don't put any text in your label in the storyboard, or it will want to size to that text. So delete the placeholder text from the storyboard, set the constraints and then you will be good to go.
Upvotes: 0
Reputation: 104082
This sounds like a consequence of auto layout -- when using it, you shouldn't set frames at all, instead you should adjust the constraints. You can make an IBOutlet to the width constraint of your label, and adjust its constant value in code.
Upvotes: 3