Search code examples
iosswiftuiimageviewuinavigationbarnslayoutconstraint

Add Constraint to navigationBar Programmatically Swift


I'm trying to add constraint to navigation bar, I have UIImageView, which has width, height and is centered horizontally, I want to add vertical space between UIImage and navigationBar to 0, I'm trying this for like 1 hour and couldn't figure out how, i tried adding constraint to UIView, and added constant of navbarHeight + statusBarHeight, and it worked, but I want to make relationship between imageview and navbar

let verticalSpace = NSLayoutConstraint(item: image, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0)
view.addConstraint(verticalSpace) // this works

Solution

  • try with topLayoutGuide

    let verticalSpace = NSLayoutConstraint(item: image,  
                                           attribute: .Top,  
                                           relatedBy: .Equal,  
                                           toItem: self.topLayoutGuide,  
                                           attribute: .Bottom,  
                                           multiplier: 1, constant: 0)  
    

    The above constraint explanation:

    simply its called: vertical space between image.Top & self.topLayoutGuide.Bottom = 0

    that means Top constraint of image view attached with a Bottom attribute of topLayoutGuide with constant 0.

    You can use anchors as well to make this possible for iOS 10+

    if #available(iOS 11.0, *) {
       image.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
    } else {
       image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
    }