UILabel SizetoFit After Specifying Number of Lines?

320 views Asked by At

I would like to create a UILabel programmatically after specifying the number of lines. I am using Swift. I have the following code:

let newLabel = UILabel()
newLabel.text = "Hello There"
newLabel.font = UIFont.systemFont(ofSize: 16)
newLabel.numberOfLines = 2
newLabel.lineBreakMode = .byWordWrapping
newLabel.sizeToFit()
newLabel.frame.origin.x = 100
newLabel.frame.origin.y = 500
view.addSubview(newLabel)

The problem is that the label has the text on one line, rather than two lines. I have to use sizeToFit because the fontSize is actually dynamic (it is not always 16). How can I make sure that the label is 2 lines? Thanks.

2

There are 2 answers

0
andesta.erfan On

You are not specifying exact frame of your UILabel.so your view just get any width it wants.you can use this for getting result:

newLabel.frame = CGRect(x: 100, y: 500, width: newLabel.frame.width - 1, height: newLabel.frame.height * 2)

But that's not very good and I suggest using AutoLayout

0
AbhishekS On

There are many things you can do to break line. 1) You can use "\n" in between the words. But not sure about your usecase and whether this make sense. 2) Thought not recommended you can define the width of the label. 3) Use numberOfLines = 0, if you can go to more than 2 lines. However, if you only want 2 lines then give numberOfLines = 2.

Also use Constraints something like below and not frame:

 private let newLabel: UILabel = {
     let label = UILabel()
     label.translatesAutoresizingMaskIntoConstraints = false
     label.text = "Hello There"
     label.font = UIFont.systemFont(ofSize: 16)
     label.numberOfLines = 0

     return label
   }()

   view.addSubview(newLabel)

   NSLayoutConstraint.activate([
      newLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 500),
      newLabel.leadingAnchor.constraint(equalTo:view.leadingAnchor, constant: 100),
      newLabel.widthAnchor.constraint(equalToConstant: 70)
   ])