Resize UILabel for text

I have a UILabel in my cell subclass, which supposedly should contain a header. The size of the header can be of different lengths, and therefore I need to resize the UILabel so that it matches the text and so that the text is not long, I also need to set maxHeight. The width should be the same. How to create such code in swift in a subclass of tableViewCell?

While I have it in awakeFromNib

theTitleLabel?.font = UIFont(name: "HelveticaNeue", size: 13) theTitleLabel?.textColor = UIColor(rgba: "#4F4E4F") theTitleLabel?.numberOfLines = 0 theTitleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail 
+5
source share
4 answers

The easiest way to do this is to use autodetection restrictions. You are using awakeFromNib , so I assume that you have this cell somewhere in your interface builder (xib file or storyboard).

If you can avoid this, never tweak your views in your code. This is much easier to do in Interface Builder.

  • Find your shortcut and configure its attributes (font, color, line break mode, etc.) in the interface builder.

  • Add a width constraint (or left and right margins, depending on what you want).

  • Add a height constraint, change its ratio from = (equals) to < (less than) .

You are ready, the code is not needed.

+4
source
  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); 
+6
source

Swift 2 version , from Sieglesworth'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) 
+3
source
 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() 
-1
source

Source: https://habr.com/ru/post/1207982/


All Articles