对象不受限于中心y锚的底部锚

问题描述 投票:0回答:1

我的快速代码正在尝试将对象限制在中心y锚的底部。构建代码并在iPad上运行时。那没有做。您可以在下图中看到正在显示的内容。显然,该对象没有触摸屏幕的中心。图像上的红色标记是我要寻找的。

        NSLayoutConstraint.activate([





        box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.20),
        box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.2),
        box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      box.bottomAnchor.constraint(equalTo: view.centerYAnchor),

        ])

enter image description here

swift ipad constraints center nslayoutconstraint
1个回答
0
投票

为了以编程方式使用约束,请记住将对象中的translatesAutoresizingMaskIntoConstraints设置为false

let imageAlert: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleToFill
        iv.backgroundColor = .white
        iv.image = UIImage(named: "soup")
        iv.translatesAutoresizingMaskIntoConstraints = false //here
        return iv
    }()

另一个常见错误是未将组件添加到视图中

func addComponents() {
        self.addSubview(container)
        container.addSubview(quit)
        container.addSubview(imageAlert)
        container.addSubview(alertLabel)
        container.addSubview(alertButtonAccept)
        container.addSubview(alertButtonCancel)

    }

同样,如果您没有使用自定义视图插入对象,请使用self

NSLayoutConstraint.activate([

    box.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.20),
    box.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.2),
    box.centerXAnchor.constraint(equalTo: self.centerXAnchor),
  box.bottomAnchor.constraint(equalTo: self.centerYAnchor)

    ])
© www.soinside.com 2019 - 2024. All rights reserved.