iOS Swift UILabel Multiline Text Display

iOS Swift UILabel Multiline Text Display


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "Main View"
        
        //Create a label with multiline text
        addLabel1()
        
        //Create a label with ZERO multiline text
        addLabel2()
        
   }
    
    //Issue here is that one of the lines will be hidden
    func addLabel1(){
        
        let myLabel = UILabel()
        myLabel.textColor = UIColor.red
        myLabel.backgroundColor = UIColor.yellow
        myLabel.numberOfLines = 2
        myLabel.text = "Hello, World!\nHello, World!\nHello, World!"
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myLabel)
        
        var allConstraints: [NSLayoutConstraint] = []
        let views = ["view": view!, "myLabel": myLabel]
        
        let horizontalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-[myLabel(200)]-(>=10)-|", metrics: nil, views: views)
        allConstraints += horizontalConstraints
        
        let verticalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-(>=40)-[myLabel(>=20)]", metrics: nil, views: views)
        allConstraints += verticalConstraints
        
        NSLayoutConstraint.activate(allConstraints)
    }
    
    func addLabel2(){
        
        let myLabel = UILabel()
        myLabel.textColor = UIColor.red
        myLabel.backgroundColor = UIColor.yellow
        myLabel.numberOfLines = 0
        myLabel.text = "Hello, World!\nHello, World!\nHello, World!"
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myLabel)
        
        var allConstraints: [NSLayoutConstraint] = []
        let views = ["view": view!, "myLabel": myLabel]
        
        let horizontalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-[myLabel(200)]-(>=10)-|", metrics: nil, views: views)
        allConstraints += horizontalConstraints
        
        let verticalConstraints = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-(>=140)-[myLabel(>=20)]", metrics: nil, views: views)
        allConstraints += verticalConstraints
        
        NSLayoutConstraint.activate(allConstraints)
    }
    

}

Please Note: If the label has a height constraint, the constraint will be respected. In this case, label.numberOfLines = 0 may not work as expected. For a more complex multi-line text, UITextView may be a better fit.

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.