在UITableViewCell内动态更改标签宽度 [英] Change the label width dynamically inside a UITableViewCell

查看:104
本文介绍了在UITableViewCell内动态更改标签宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立自定义表格视图。

I am trying to build up an custom table view.

正如您在图片中看到的那样,我将标签的宽度默认设置为故事板旁边的160点并且加载表时,动态更改宽度。我通过修改cellForRowAtIndexPath委托方法来实现这一点。

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.

因此,基于日期的长度,我将Label1的宽度设置为最大利用房地产手机屏幕。

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;

但是当我加载应用程序时,所有label1都设置为故事板中设置的160点,尽管通过调试我已经看到我的代码被执行每个单元格。

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.

推荐答案

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

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.

这篇关于在UITableViewCell内动态更改标签宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆