【问题标题】:Default missing Autolayout constraints when added programmatically以编程方式添加时默认缺少自动布局约束
【发布时间】:2019-01-18 18:09:54
【问题描述】:

我忘记在我的自动布局中添加一个 x 组件,但我仍然能够看到视图。我想知道自动布局在以编程方式使用时如何/是否生成默认约束,因为在 IB 中会出现错误。调试控制台中也不会打印任何错误。

我注意到,当我不指定 x 组件时,视图将始终锚定到其父视图。是否有文档说明缺少约束时的默认值是什么?

import UIKit
import PlaygroundSupport
//
class MyViewController : UIViewController {

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        self.view = view
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let outBox = UIView()
        outBox.backgroundColor = UIColor.blue
        view.addSubview(outBox)
        outBox.translatesAutoresizingMaskIntoConstraints = false
        outBox.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        outBox.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        outBox.widthAnchor.constraint(equalToConstant: 200).isActive = true
        outBox.heightAnchor.constraint(equalToConstant: 200).isActive = true

        let inBox = UIView(frame: CGRect(x: 100, y: 2000, width: 10, height: 10))
        inBox.backgroundColor = UIColor.red
        outBox.addSubview(inBox)
        inBox.translatesAutoresizingMaskIntoConstraints = false
        inBox.topAnchor.constraint(equalTo: outBox.topAnchor).isActive = true
        inBox.bottomAnchor.constraint(equalTo: outBox.bottomAnchor).isActive = true
        inBox.widthAnchor.constraint(equalToConstant: 25).isActive = true
        // NO x-constraint component.. Should raise missing constraints error.
    }
}

PlaygroundPage.current.liveView = MyViewController()

【问题讨论】:

    标签: swift autolayout nslayoutconstraint


    【解决方案1】:

    关键不在此处设置框架

    let inBox = UIView(frame: CGRect(x: 100, y: 2000, width: 10, height: 10))
    

    但它就在这里

    inBox.translatesAutoresizingMaskIntoConstraints = false
    

    该行忽略了框架到约束的内部转换并将它们默认为零基础,约束不足并不意味着您看不到视图,例如您可以在 IB 中执行相同操作并且仍然看到红色的视图边界和运行后也一样,但这并不意味着它已正确设置,这作为最终约束将被转换为框架,所以这是一个关于从零开始的巧合

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多