如何设置约束,让一个标签填满整个屏幕?

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

我在 Swift 中以编程方式设置标签约束时遇到问题。我想让标签填满整个屏幕。但是我不知道怎么办。

感谢您的帮助。

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
        
    }
}

您可以将此扩展程序用于您的所有视图

extension UIView {
    public func alignAllEdgesWithSuperview() {
        guard let superview = self.superview else {
            fatalError("add \(self) to a superview first.")
        }
        self.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            self.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
            self.topAnchor.constraint(equalTo: superview.topAnchor),
            self.bottomAnchor.constraint(equalTo: superview.bottomAnchor)
        ]
        NSLayoutConstraint.activate(constraints)
    }
}    

和用法

view.addSubview(someView)
someView.alignAllEdgesWithSuperview()