Adding View Programatically With Auto Layout Gives 'NSGenericException', reason: 'Unable to install constraint on view

后端 未结 3 1556
暖寄归人
暖寄归人 2021-02-09 18:37

I am adding a view as a subview using [self.view addSubview:myView]. This works fine in portrait mode. However, it doesn\'t work at all in landscape. How do I add l

3条回答
  •  北海茫月
    2021-02-09 19:10

    From your code above, there are 2 issues. 1. The constraint should be added to the parentview (self.view or self.view.superview as appropriate). 2. The items which are part of the myConstraint should be present in the view hierarchy to which you add your constraints.

    My suggestion would be to check if your myConstraint can be formed with _preView and self.view , add the _preView to self.view as a subview and then add the myConstraint to self.view.

    Also, the constraints should ideally be placed in -(void)updateConstraints method in your view (if you have a custom view) and you should call [self setNeedsUpdateConstraints]; in your view whenever you want the updateConstraints to be called on your view (after initializing your view, after rotation etc). You won't be calling updateConstraints directly.

提交回复
热议问题