如何将某些东西约束到中心顶部锚点

how to constraint something to the center top anchor

在我下面的代码中,我试图将某些东西限制在 uiscreen 中心点的顶部。我在下面添加了我正在寻找的图像。下面的代码是我尝试过的,它把它固定在屏幕的中心,并在屏幕中间有一个对象。

import UIKit

class ViewController: UIViewController {
    var box = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        box.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(box)
        box.backgroundColor = .systemPink
        NSLayoutConstraint.activate([

            box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier : 0.25),
            box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier : 0.25),
            box.centerXAnchor.constraint(equalTo: view.centerXAnchor ),
            box.centerYAnchor.constraint(equalTo: view.centerYAnchor),


        ])
    }


}

删除这个:

box.centerYAnchor.constraint(equalTo: view.centerYAnchor )

添加:

box.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20) //Add padding accordingly

按原样添加以下解决方案...它将帮助您 运行 完美...!!!

    override func viewDidLoad() {
        super.viewDidLoad()

        box.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(box)
        box.backgroundColor = .systemPink
        NSLayoutConstraint.activate([

            box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier : 0.25),
            box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier : 0.25),
            box.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
            box.centerXAnchor.constraint(equalTo: view.centerXAnchor )
            ])
        // Do any additional setup after loading the view.
    }

注意:- 您正在添加 box.centerYAnchor.constraint(equalTo: view.centerYAnchor) 此约束,因此您无法将框居中放置。

您需要删除 centerYAnchor 约束而不是您的 box 并改为设置 bottomAnchor

删除:box.centerYAnchor.constraint(equalTo: view.centerYAnchor)

添加:box.bottomAnchor.constraint(equalTo: view.centerYAnchor)

正确的约束条件:

NSLayoutConstraint.activate([
    box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25),
    box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.25),
    box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    box.bottomAnchor.constraint(equalTo: view.centerYAnchor)
])