user3766930 user3766930 - 2 months ago 6
iOS Question

how can I apply the NSLayoutConstraints to the element so that it is always in the middle of the element below him?

In my storyboard I have a

MapView
stretched to the borders of my screen. But there's a possibility to show up the keyboard, so then I update the constraints and the map shrinks in height.

This is my method responsible for that:

func keyboardWillChangeFrame(notification: NSNotification) {
let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

if(isKeyboardShown == true)
{
bottomConstraint.constant = CGRectGetHeight(view.bounds) - endFrame.origin.y+49
self.view.layoutIfNeeded()
isKeyboardShown = false
} else {
bottomConstraint.constant = CGRectGetHeight(view.bounds) - endFrame.origin.y
self.view.layoutIfNeeded()
isKeyboardShown = true
}
}


It works fine. Now I want to add the
UIImageView
that is always centered on the map, no matter if the keyboard is visible or not. I thought it's enough to center the image in the perfect center of the map.

It so far looks like this:

enter image description here

I managed to add somehow the constraint on the
Y
axis:

enter image description here

but what about
X
?

I tried adding it here:

enter image description here

but the
align
option is greyed out...

How can I add constraints so that the image is always centered no matter how the map is shrinked?

Answer

Try Ctrl+dragging from the image view to the map, and clicking Center Horizontally.

You also might have a conflict with your Top Space to: Top Layout... constraint and your Align Center Y to: Map View constraint. It sounds like you just want the center Y constraint, since when your map grows / shrinks your image won't always be 192 from the top if it's centered on the map.