Search code examples
swiftuilabelnslayoutconstraint

Multiline text not fitting into UILabel


I have this code :

class ViewController: UIViewController {
    private var nameLabel = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        updateLable()
    }

    func updateLable ()  {
        nameLabel = UILabel(frame: view.frame)
        nameLabel.text = "Michael Dell Arron Henry Mitchell duve soooooooooooooooooooooooooc"
        nameLabel.backgroundColor = .green
        nameLabel.numberOfLines = 0
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(nameLabel)
        NSLayoutConstraint.activate([
            nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0),
            nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0)
            
        ])
        
        nameLabel.isHidden = false
        
    }

}

I am unable to fit the text into the label. I checked on other comments with numberOfLines = 0 and sizeToFit() but that seems not to be working.

This is what it looks like currently:

Label overflows into horizontal sides of screen


Solution

  • You need to constrain the width of the label in order for it to wrap. You can either:

    1. Set the width constraint

    NSLayoutConstraint.activate([
        nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0),
        nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0),
        nameLabel.widthAnchor.constraint(equalToConstant: 100) /// here!
    ])
    

    Result:

    Label with 7 lines because it is constrained to 100 width

    2. Set the leading and trailing constraint to the superview

    NSLayoutConstraint.activate([
        nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0), /// you can delete this
        nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0),
                
        /// here!
        nameLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
        nameLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
    ])
    

    Result:

    Label with 2 lines, because its horizontal edges are constrained to the superview