简体   繁体   中英

Change the label width dynamically inside a UITableViewCell

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.

在此处输入图片说明

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.

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.

您还可以以编程方式创建和放置UILabel,这样iOS的自动布局将不会干扰您的框架更改。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM