简体   繁体   English

调整UILabel的高度以适合文本

[英]Resizing the height of UILabel to fit text

I have UILabel in my Cell Subclass which is suppose to hold a title. 我在我的Cell Subclass中有UILabel,假设有一个标题。 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. 标题的大小可以是各种长度,因此我需要调整UILabel的大小以适应文本,并防止文本不长,我还需要能够设置maxHeight。 The width should be the same. 宽度应该相同。 How can I create such code in swift in a tableViewCell subclass? 如何在tableViewCell子类中的swift中创建这样的代码?

So far I have this in awakeFromNib 到目前为止,我在awakeFromNib中有这个

theTitleLabel?.font = UIFont(name: "HelveticaNeue", size: 13)
theTitleLabel?.textColor = UIColor(rgba: "#4F4E4F")
theTitleLabel?.numberOfLines = 0
theTitleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
    CGSize maximumLabelSize = CGSizeMake(MAX_WIDTH, MAX_HEIGHT);
    CGSize expectedSize = [lbl sizeThatFits:maximumLabelSize];

    CGSize s = CGSizeMake(STATIC_WIDTH, expectedSize.height);
    yourLabel.frame = CGRectMake(yourLabel.frame.origin.x, nameLbl.frame.origin.y, s.width, s.height);

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). 您正在使用awakeFromNib ,因此我假设您在Interface Builder(xib或storyboard文件)中的某个位置使用了该单元格。

If you can avoid it, never set up your views in your code. 如果可以避免,请不要在代码中设置视图。 It's far easier to do it in the Interface Builder. 在Interface Builder中完成它要容易得多。

  1. Find your label and set up its attributes (font, color, line break mode etc.) in the Interface Builder. 在Interface Builder中找到您的标签并设置其属性(字体,颜色,换行模式等)。

  2. Add a width constraint (or constraints to left and right margins, depending on what you want). 添加宽度约束(或左边和右边距的约束,具体取决于你想要的)。

  3. Add a height constraint, change its relation from = (equals) to < (less than) . 添加高度约束,将其关系从= (equals)更改为< (less than)

You are done, no code is needed. 你完成了,不需要代码。

Swift 2 version, from Zigglzworth's answer : Swift 2版本,来自Zigglzworth的回答:

let maximumLabelSize = CGSizeMake(maxWidth, maxHeight);
let expectedSize = theLabel.sizeThatFits(maximumLabelSize)

theLabel.frame = CGRectMake(theLabel.frame.origin.x, theLabel.frame.origin.y, expectedSize.width, expectedSize.height)
let lblMassage = UILable()        
lblMassage.text ="Resizing the height of UILabel to fit text.................."
lblMassage.numberOfLines = 0
lblMassage.lineBreakMode = NSLineBreakMode.byTruncatingTail
lblMassage.preferredMaxLayoutWidth = 190
lblMassage.sizeToFit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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