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
Add Swift Constraints Programmatically Source Code. After you create a Xcode project, edit ViewController.swift file use below source code. You will need to override the viewWillTransition function, this function is triggered when the screen orientation is changed, so we exchange the screen width and height value in that function.
Auto Layout in Swift: Writing constraints programmatically. Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions. Can you imagine a world without Auto Layout?
// Activate bottom constraint to enable it. // Set and activate left, right constraint to backgroundView. /* Create red view and add it as background view's subview, use NSLayoutAnchor class to add constraints to it, so the constraint is relative to backgroundView.
Add Constraints To UIView Object Use Visual Format Language. Besides the above two methods, you can also use Visual Format Language to add constraints to the UIView object. Visual format language is just a text string that defines the constraints layout meanings.
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
}
llkenny's answer for iOS 11.0+ :
image.topAnchor.constraint(equalTo:
view.safeAreaLayoutGuide.topAnchor).isActive = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With