Is there any way to add constraint between a view and the top layout guide in a xib file?

Solution 1:

You should refer the following example, this will definitely help you for your problem. I got this from http://developer.apple.com .

[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = myViewController.topLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);

[myViewController.view addConstraints:
    [NSLayoutConstraint constraintsWithVisualFormat: @"V:[topGuide]-20-[button]"
    options: 0
    metrics: nil
    views: viewsDictionary]
];

Solution 2:

Here is my alternative solution.

Find a UIView as a pivot, set its top layout constraint a fixed vertical space to container's top.

Control-Drag this layout constraint as an IBOutlet, such as

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayoutConstraint;

Finally, just override viewWillLayoutSubviews method of UIViewController like following

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    self.topLayoutConstraint.constant = [self.topLayoutGuide length] + YOUR_TOP_CONSTRSINT;
}

All the other views' top constraint are based this pivot view, all done :)

Solution 3:

From iOS 9 you can also do it more simple with topLayoutGuide's anchors:

  • Swift 3

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

  • ObjC

[controller.view.topAnchor constraintEqualToAnchor:controller.topLayoutGuide.bottomAnchor].active = YES;