Reputation: 840
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
Reputation: 9
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
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
Reputation: 388
llkenny's answer for iOS 11.0+ :
image.topAnchor.constraint(equalTo:
view.safeAreaLayoutGuide.topAnchor).isActive = true
Upvotes: 10
Reputation: 146
With anchors:
image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
Upvotes: 3