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

前端 未结 8 1223
予麋鹿
予麋鹿 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:59

    As the error states, you must add the constraint to a view such that the views involved in the constraint are the view you're adding it to or a subview of that view. In the case of your code above, you should be adding that constraint to self, rather than [self internalView]. The reason it doesn't work as written is one of the views involved in the constraint (self) is not in the view hierarchy if you consider only [self internalView] and below).

    For more details, see the discussion section of the documentation on the addConstraint: method.

    Here is your line of code, fixed as I suggest:

    UIView* internalView = [[UIView alloc] initWithFrame:CGRectZero];
    internalView.translatesAutoresizingMaskIntoConstraints = NO;
    [self setInternalView:internalView];
    
    [self addConstraint: [NSLayoutConstraint constraintWithItem: [self internalMapView]
                                             attribute: NSLayoutAttributeCenterX
                                             relatedBy: NSLayoutRelationEqual
                                             toItem: self
                                             attribute: NSLayoutAttributeCenterX
                                             multiplier: 1
                                             constant: 0]];
    
    0 讨论(0)
  • 2020-11-30 02:59

    Short answer: swap parent and child view.
    Assuming self is the parent view:

    • bad: [subview addConstraint [NSLayoutConstraint constraintWithItem:self...

    • good: [self addConstraint [NSLayoutConstraint constraintWithItem:subview...


    Swift

    subview.translatesAutoresizingMaskIntoConstraints = false
    self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-0-[subview]-0-|",
        options: .DirectionLeadingToTrailing,
        metrics: nil,
        views: ["subview":subview]))
    

    Obj-C

    [subview setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self addConstraints:[NSLayoutConstraint
                          constraintsWithVisualFormat:@"H:|-0-[subview]-0-|"
                          options:NSLayoutFormatDirectionLeadingToTrailing
                          metrics:nil
                          views:NSDictionaryOfVariableBindings(subview)]];
    
    0 讨论(0)
提交回复
热议问题