Search code examples
iosobjective-cnslayoutconstraint

NSLayoutConstraint `view is not a key in the views dictionary`


Intro:

Yes, I have looked through all of the questions that relates to the subject, none of the answers helped. The code below keep throwing me a NSInvalidArgumentException exception, and I still can't see what's wrong with it.

Question:

I've tried everything I possibly could try. It's still crashing with the same error message as always, which is; 'Unable to parse constraint format: sceneView is not a key in the views dictionary.'.

Here's what I do:

- (SCNView *)sceneView { // Lazy Load
  if (_sceneView == nil) {
    _sceneView = [[SCNView alloc] initWithFrame:self.bounds];
    _sceneView.backgroundColor = [UIColor blackColor];
    _sceneView.scene = self.scene; // Load scene
    _sceneView.translatesAutoresizingMaskIntoConstraints = NO;

  }
  return _sceneView;
}

Then in -(void)commonInit, I add it:

if ([self.sceneView isDescendantOfView:self] == NO) {
    [self addSubview:self.sceneView];
  }

  [self.sceneView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[sceneView]|"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:NSDictionaryOfVariableBindings(self.sceneView)]];

Right after that, it terminates with exception. Why?


Solution

  • Using self. is just for calling a method that returns an object, it isn't something you can use as a key, which you are doing wrong. Use below way, it will fix your crash issue:

    [self.sceneView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_sceneView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sceneView)]];