簡體   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