【问题标题】:View not displaying and centralising with autolayout视图不显示和自动布局集中
【发布时间】:2020-04-21 10:02:49
【问题描述】:

我想以编程方式在我的视图控制器中添加一个视图并集中它。我将视图作为子视图添加到父视图并启用自动布局但它没有显示。

import UIKit

class ViewController: UIViewController {
    lazy var newView:UIView = {
        let view = UIView()
        view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        view.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
        return view
    }()


    let titleLable = UILabel()
    let bodyLabel = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(newView)
        newView.translatesAutoresizingMaskIntoConstraints = false


        newView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        newView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true



    }


}

【问题讨论】:

  • 您应该使用基于框架的布局或自动布局。不是都。如果您想使用自动布局,则应按照 Roman 在答案中的建议进行操作。

标签: ios swift autolayout


【解决方案1】:

试试这个方法

NSLayoutConstraint(item: newView,
                   attribute: NSLayoutConstraint.Attribute.centerX,
                   relatedBy: NSLayoutConstraint.Relation.equal,
                   toItem: view,
                   attribute: NSLayoutConstraint.Attribute.centerX,
                   multiplier: 1,
                   constant: 0).isActive = true

NSLayoutConstraint(item: newView,
                   attribute: NSLayoutConstraint.Attribute.centerY,
                   relatedBy: NSLayoutConstraint.Relation.equal,
                   toItem: view,
                   attribute: NSLayoutConstraint.Attribute.centerY,
                   multiplier: 1,
                   constant: 0).isActive = true

【讨论】:

    【解决方案2】:

    newView 缺少大小限制。您使用newView.translatesAutoresizingMaskIntoConstraints = false 删除了它们。要恢复所有必需的约束,请将以下几行添加到 viewDidLoad

    newView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    newView.heightAnchor.constraint(equalToConstant: 200).isActive = true
    

    【讨论】:

      【解决方案3】:

      问题来了…… 首先,你设置 newView 的框架, 其次,您还设置 translatesAutoresizingMaskIntoConstraints = false 所以 Xcode 不明白你想设置什么框架或约束。 所以如果你设置了框架,那么你以后就不能再在它上面添加约束了。

      所以根据您的需要,最好的解决方案是:

      view.addSubview(newView)
      newView.translatesAutoresizingMaskIntoConstraints = false
      
      newView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      newView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
      newView.widthAnchor.constraint(equalToConstant: 200).isActive = true
      newView.heightAnchor.constraint(equalToConstant: 200).isActive = true
      

      【讨论】:

      • 但是如何获取newView的宽度和高度
      • @Darotudeen 是 200,或者你是什么意思?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多