1

I have a UILabel with dynamic width and dynamic string which I am getting from server. Now I want to set this string to label as text. Also I need to set number of lines to label. As I am getting dynamic string so I am not sure how much characters can be set in a line.

I found similar answers but those are not giving me accuracy as I need.

Code Hunter
  • 10,075
  • 23
  • 72
  • 102

2 Answers2

1

Set number of lines to 0, this will make it dynamic. You also need to make your UILabel sizeToFitmyUiLabel.sizeToFit()

0

If you for some reason need the number of lines, you can use following extension on UILabel:

extension UILabel {

    func linesNeeded() -> Int {
        self.layoutIfNeeded()
        let myText = self.text! as NSString
        let boundingRectangle = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let labelSize = myText.boundingRect(with: boundingRectangle,
                                            options: .usesLineFragmentOrigin,
                                            attributes: [NSAttributedStringKey.font: self.font],
                                            context: nil)
        return (labelSize.height / self.font.lineHeight)
    }
}

However, if you don't need the height, you just want to allow the label to show the whole text, you should set label.numberOfLines = 0 which will allow the label to grow as needed.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90