简体   繁体   中英

Resizing the height of UILabel to fit text

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?

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
    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).

If you can avoid it, never set up your views in your code. It's far easier to do it in the Interface Builder.

  1. Find your label and set up its attributes (font, color, line break mode etc.) in the 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) .

You are done, no code is needed.

Swift 2 version, from Zigglzworth's answer :

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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