Swift: addSubview 放在上一个视图上

Swift: addSubview is placed on previous view

我使用此代码向父级添加两个视图:

let view0 = StarClass.createMyClassView()
parent.addSubview(view0)

let view1 = StarClass.createMyClassView()
parent.addSubview(view1)

这段代码工作正常,但是 view1 没有放在 view0

的底部

view1 置于 view0

我想在 view0

的底部添加 view1

我怎么可以?

您可以使用自动版式实现这一点,请参见下面的示例。

    let view0 = StarClass.createMyClassView()
    view0.translatesAutoresizingMaskIntoConstraints = false // Enables autolayout

    parent.addSubview(view0)

    let view1 = StarClass.createMyClassView()
    view1.translatesAutoresizingMaskIntoConstraints = false 
    parent.addSubview(view1)

    NSLayoutConstraint.activate([
        view0.leftAnchor.constraint(equalTo: parent.leftAnchor), // Set layout for view0
        view0.rightAnchor.constraint(equalTo: parent.rightAnchor),
        view0.topAnchor.constraint(equalTo: parent.topAnchor),
        view0.heightAnchor.constraint(equalToConstant: 100),

        view1.leftAnchor.constraint(equalTo: parent.leftAnchor), // Set layout for view1
        view1.rightAnchor.constraint(equalTo: parent.rightAnchor),
        view1.topAnchor.constraint(equalTo: view0.bottomAnchor), // below view0
        view1.heightAnchor.constraint(equalToConstant: 100)
        ])