Centering subview's X in autolayout throws “not prepared for the constraint”

前端 未结 8 1222
予麋鹿
予麋鹿 2020-11-30 02:09

I have a custom UIView subclass which is being initialized via a nib.

In -awakeFromNib, I\'m creating a subview and attempting to center it in its super

相关标签:
8条回答
  • 2020-11-30 02:36

    First add your subView and then add your constraints like this

    addSubview(yourSubViewHere)
    yourSubViewHere.translatesAutoresizingMaskIntoConstraints = false
    
    addConstraint(NSLayoutConstraint(....
    
    0 讨论(0)
  • 2020-11-30 02:48

    For others who come here: I got this error, because I added the constraints before I added the subviews to the hierarchy.

    0 讨论(0)
  • 2020-11-30 02:53

    As @CharlesA points out in his answer the problem is that the view you are adding is not in the proper view hierarchy. His answer is a good one, but I'm going to throw in some detail for a particular use-case that caused this problem for me:

    I had this happen when attempting to add constraints to a view whose view controller I had instantiated using instantiateViewControllerWithIdentifier. To solve the problem, I used [childViewController didMoveToParentViewController:self]. This added the view into the view hierarchy that was referenced by my constraint.

    0 讨论(0)
  • 2020-11-30 02:55

    In my case, it was solved by using root view as a container of constraints instead of a currently created view.

    I mean, use inside viewController

    view.addConstraints([leftConstraintImage, topConstraintImage]) instead of imageView.addConstraints...

    0 讨论(0)
  • 2020-11-30 02:57

    This is an old question but I want to point out this line from the docs:

    When developing for iOS 8.0 or later, set the constraint’s isActive property to true instead of calling the addConstraint(_:) method directly. The isActive property automatically adds and removes the constraint from the correct view.

    At the very least, this will remove one point of failure since you no longer need to worry about calling addConstraint on the wrong view

    0 讨论(0)
  • 2020-11-30 02:58

    Additional Tips:

    I have a newly developed App which running fine on iOS7 but get error on iOS8 "The view hierarchy is not prepared for the constraint".

    Read some other post said that the (sub)views need to be added before create constraints. I did that but still got the error.

    Then I figured out that I should create constraints under -(void)viewDidAppear instead of viewDidLoad

    0 讨论(0)
提交回复
热议问题