Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crash on AutoLayout: Location anchors require being paired

The app is crashing on Location anchors require being paired.. I would like to fix it, however no matter how many times did I manually tested the app with this view, I've never run into the crash (got only logs on Crashlytics). Anyone knows what may be wrong here, under what circumstances the crash may happen?

The property centerYConstraint is required because later it allows the user to move the view up/down.

Part of MyView.m file. The crash happens on setting self.centerYConstraint.

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.centerYConstraint = [self.view.centerYAnchor constraintEqualToAnchor:self.parentViewController.view.centerYAnchor 
                                                      constant:self.view.center.y - self.parentViewController.view.center.y];
    self.centerYConstraint.active = YES;
}

Crash log:

Fatal Exception: NSInvalidArgumentException
NSLayoutConstraint for <NSLayoutYAxisAnchor:0x16764ae0 "MyView:0x18e6b900.centerY">: 
A constraint cannot be made from <NSLayoutYAxisAnchor:0x16764ae0 "MyView:0x18e6b900.centerY"> to a constant. 
Location anchors require being paired.
like image 846
Nat Avatar asked Feb 10 '17 11:02

Nat


1 Answers

This exception happens when constraintEqualToAnchor:self.parentViewController.view.centerYAnchor gives nil, which might be when self.parentViewController.view is nil, or self.parentViewController is nil.

All hierarchy logic is not clear from description, but the following does solve the issue (assuming that superview is a view of parent controller, otherwise just some more conditions should be added).

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.centerYConstraint = [self.view.centerYAnchor constraintEqualToAnchor:self.superview.centerYAnchor 
                                                      constant:self.view.center.y - self.superview.center.y];
    self.centerYConstraint.active = YES;
}
like image 179
Asperi Avatar answered Sep 22 '22 12:09

Asperi