繁体   English   中英

调整UILabel的高度以适合文本

[英]Resizing the height of UILabel to fit text

我在我的Cell Subclass中有UILabel,假设有一个标题。 标题的大小可以是各种长度,因此我需要调整UILabel的大小以适应文本,并防止文本不长,我还需要能够设置maxHeight。 宽度应该相同。 如何在tableViewCell子类中的swift中创建这样的代码?

到目前为止,我在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);

最简单的方法是使用自动布局约束。 您正在使用awakeFromNib ,因此我假设您在Interface Builder(xib或storyboard文件)中的某个位置使用了该单元格。

如果可以避免,请不要在代码中设置视图。 在Interface Builder中完成它要容易得多。

  1. 在Interface Builder中找到您的标签并设置其属性(字体,颜色,换行模式等)。

  2. 添加宽度约束(或左边和右边距的约束,具体取决于你想要的)。

  3. 添加高度约束,将其关系从= (equals)更改为< (less than)

你完成了,不需要代码。

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