2

I am trying to build up an custom table view.

enter image description here

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.

enter image description here

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.

enter image description here

Moreover, if I switch between the tabs, the label is restored to the abnormal status again.

enter image description here

4

3 回答 3

3

这听起来像是自动布局的结果——使用它时,您根本不应该设置框架,而是应该调整约束。您可以为标签的宽度约束创建一个 IBOutlet,并在代码中调整其常量值。

于 2013-11-07T00:15:15.747 回答
0

您还可以通过编程方式创建和定位 UILabel,这样 iOS 自动布局就不会干扰您的帧更改。

于 2014-07-01T04:13:56.330 回答
0

如果您使用自动布局,您可以只设置 x 和 y 位置,然后不设置高度和宽度,标签将正确调整自身大小以适合其内容。如果您使用的是 Xibs 或 Storyboard,请注意,不要在 Storyboard 的标签中放置任何文本,否则它会希望调整为该文本的大小。所以从情节提要中删除占位符文本,设置约束,然后你就可以开始了。

于 2013-11-07T00:22:26.690 回答