Search code examples
swiftuilabel

How to set constraints so that a label fills the entire screen?


I'm having trouble setting constraints to a label programmatically in Swift. I want the label to fill the entire screen. But I dont know how to do.

Thank you for your help.


Solution

  • class ViewController: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            let label = UILabel()
            label.text = "Hello"
            label.backgroundColor = UIColor.yellow
                
            self.view.addSubview(label)
            label.translatesAutoresizingMaskIntoConstraints = false
            
            let width: NSLayoutConstraint
            width = label.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1)
    
            let top: NSLayoutConstraint
            top = label.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
            
            let bottom: NSLayoutConstraint
            bottom = label.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
                
    
            width.isActive = true
            bottom.isActive = true
            top.isActive = true
            
        }
    }
    

    enter image description here