Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 569
Peter Pik Avatar asked Nov 30 '14 14:11

Peter Pik


2 Answers

    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);
like image 86
Zigglzworth Avatar answered Oct 26 '22 15:10

Zigglzworth


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.

like image 31
Sulthan Avatar answered Oct 26 '22 16:10

Sulthan