调整UILabel的高度以适合文本 [英] Resizing the height of UILabel to fit text
问题描述
我的Cell Subclass中有UILabel,假设有一个标题。标题的大小可以是各种长度,因此我需要调整UILabel的大小以适应文本并防止文本不长,我还需要能够设置maxHeight。宽度应该相同。如何在tableViewCell子类中的swift中创建这样的代码?
I have UILabel in my Cell Subclass which is suppose to hold a title. The size of the title can be various lengths and therefor I need to resize the UILabel to fit the text and to prevent that the text is not to long I also need to be able to set maxHeight. The width should be the same. How can I create such code in swift in a tableViewCell subclass?
到目前为止,我在awakeFromNib中有这个
So far I have this in awakeFromNib
theTitleLabel?.font = UIFont(name: "HelveticaNeue", size: 13)
theTitleLabel?.textColor = UIColor(rgba: "#4F4E4F")
theTitleLabel?.numberOfLines = 0
theTitleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
推荐答案
最简单的方法是使用autolayout约束。您正在使用 awakeFromNib
,因此我假设您在Interface Builder中的某个位置(xib或storyboard文件)。
The easiest way to do that is using autolayout constraints. You are using awakeFromNib
, so I assume you have that cell somewhere in your Interface Builder (xib or storyboard file).
如果可以避免,请不要在代码中设置视图。在Interface Builder中更容易实现。
If you can avoid it, never set up your views in your code. It's far easier to do it in the Interface Builder.
-
找到你的标签并设置它的属性(字体,颜色,线条)接口生成器中的中断模式等。
Find your label and set up its attributes (font, color, line break mode etc.) in the Interface Builder.
添加宽度约束(或左边和右边距的约束,具体取决于你想要的内容)。
Add a width constraint (or constraints to left and right margins, depending on what you want).
添加高度约束,将其关系从 =(等于)
更改为< ; (小于)
。
Add a height constraint, change its relation from = (equals)
to < (less than)
.
完成后,无需代码。
这篇关于调整UILabel的高度以适合文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!