自动布局: 添加约束到管理视图而不是顶部布局指南?

我有一个 UIView 在我的 UIViewController 在故事板,我想添加一个约束的空间,视图从顶部边缘的距离。

现在,当我像往常一样通过 ctrl + 拖动到 ViewController 的主视图时,我只能选择将其设置为 top 布局指南。

这对我来说是个问题,因为在应用程序的某一点上,我将把主视图向上移动20-50px 左右,然后发生的事情是,我的视图将不会移动... 因为它没有与“超视图”对齐。

我如何在故事板中手动做到这一点,还是必须通过编程方式添加它?

我用的是 xcode 6。

47638 次浏览

You should be able to do it by highlighting the view you want in the storyboard and then selecting Editor > Pin > Top Space to Superview in the top menu.


This is outdated in XCode 7, see @PaulGurov's answer instead.

Dan's answer works. I just wanted to state that if you set your view in storyBoard at y < 20, and configure constraints through the pin panel, it will set top to superview:

enter image description here

enter image description here

There is an arrow to the right of the constraint constant value. If you click on it, a menu pops out where you can choose what is it that you want to make your constraint relative to. If you choose 'View', than it will pin it to the top of the view.

enter image description here

I had a whole bunch of constraints already there and I just wanted to change them rather than break them. Turns out if you double click on the constraint to edit, then click on the item that has the ".Margin", you can just turn off the "Relative to Margin" by selecting that item.

Select the relative to margin

TL;DR: You can constrain to the margin by pressing the Alt key on the keyboard.


One can also add that if the view you are trying to pin is not a direct subview of the view that you want to pin it to, the suggested approach is not really valid. Let's say the view hierarchy looks like that and you want to pin the image view (Parallax Image View in this case) to the view controller's view (View in this case).

enter image description here

To do that you just Control + Drag from the Parallax Image View to the View. That presents the default choices where you can see Vertical Spacing to Top Layout Guide to pin the Parallax Image View to the top layout guide.

enter image description here

What you want is to pin it to the top (margin) of the view. To do that you have to switch to the other set of constraints by pressing Alt

enter image description here

If the height of the view is set to 0 by accident, Vertical Space to Top Layout Guide will NOT appear. Vertical Space to Bottom Layout Guide will appear, however, which must have made sense to someone inside Apple circa 2004.

None of the above answers worked for me, instead I have to do a hack to set my subview's top with superview's top instead with Top layout guide.

  • First, set the subview center vertically with superview.
  • Then, change the Center Y constraints for subview as well as superview to Top constraint.

You are good to go now.