Search code examples
swiftconstraintsanchorcenternslayoutconstraint

how to constraint something to the center top anchor


In my code below I am trying to constraint something to the top of the center point of the uiscreen. I have added a image of what I am looking for below. The code below is what I tried it pins it the center of the screen and has the object in the middle of the screen.

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),


        ])
    }


}

enter image description here


Solution

  • You need to remove centerYAnchor constraint no your box and set bottomAnchor instead.

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

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

    Correct constraints:

    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)
    ])
    

    enter image description here