Abhilasha
Abhilasha

Reputation: 949

Set UILabel height programmatically Swift not working

I m working on an app where I calculate the height of tableview cell(custom cell) dynamically.The height is calculated perfectly but the label in the cell is truncated. I also tried to set the label's height but still it shows truncated text.

enter image description here

In above screenshot you can see that the long text is not completely shown, I tried setting the label's height programmatically but it does not work. Below is the code for setting the height:

let attributes = NSMutableDictionary()
attributes.setValue(MyFonts.HELVETICA_NEUE_REGULAR_15, forKey: NSFontAttributeName)

var cellSize = labelText!.boundingRectWithSize(labelSize!, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)

labelHeight = cellSize.size.height
customCell?.subtitleLabel?.frame.size.height = labelHeight;

Kindly suggest any solution for this.

Upvotes: 0

Views: 1992

Answers (2)

Mehul Patel
Mehul Patel

Reputation: 23053

Here you have to take care of some points.

  1. Need to override layoutSubviews() in custom cell, so that you can set frame for that label text
  2. Number of line for label should be zero
  3. Dynamic calculate the height of label
  4. Dynamic cell height

I have created demo for dynamic cell.

Sample demo

enter image description here

Upvotes: 0

Neil Horton
Neil Horton

Reputation: 707

If your cell is created with auto layout you need to set

customCell?.subtitleLabel?.setTranslatesAutoresizingMaskIntoConstraints(true)

Upvotes: 2

Related Questions