nikagar4
nikagar4

Reputation: 840

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

Upvotes: 8

Views: 18613

Answers (5)

Moh Drame
Moh Drame

Reputation: 9

UICollectionViewExample code:

func mainCollectionViewConstraint() {
        NSLayoutConstraint.activate([
            mainCollectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
        mainCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        mainCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        mainCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
    ])
}

Upvotes: -1

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

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
}

Upvotes: 15

Nike Kov
Nike Kov

Reputation: 13726

In storyboard. Two constraints:

The first:

enter image description here

The second:

enter image description here

Result:

enter image description here

Upvotes: 0

Andy Novak
Andy Novak

Reputation: 388

llkenny's answer for iOS 11.0+ : image.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true

Upvotes: 10

llkenny
llkenny

Reputation: 146

With anchors:

image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true

Upvotes: 3

Related Questions