【问题标题】:How to set constraints so that a label fills the entire screen?如何设置约束以使标签填满整个屏幕?
【发布时间】:2021-12-03 01:29:11
【问题描述】:

我在 Swift 中以编程方式为标签设置约束时遇到问题。我希望标签填满整个屏幕。但我不知道该怎么做。

感谢您的帮助。

【问题讨论】:

    标签: swift uilabel


    【解决方案1】:
    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
            
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-06
        • 2014-08-12
        相关资源
        最近更新 更多