iosuiviewawakefromnibloadnibnamed

Position of Nib-loaded Subview incorrect in iOS 8


I have a custom class called CNJobMapView which is a subclass of UIView. This custom class loads a view from a nib file and adds it as a subview. I do this so that I can add a UIView object to a view in a storyboard, give it the CNJobMapView custom class, and it will appear in that view when I run the app.

I load the nib in CNJobMapView's awakeFromNib method, like so:

-(void)awakeFromNib {
  [[NSBundle mainBundle] loadNibNamed:@"CNJobMapView" owner:self options:nil];
  [self addSubview: self.contentView];
  [self internalSetup];
}

in this case, self.contentView is the main view inside the nib named "CNJobMapView". It is linked from IB.

In iOS 7 and 7.1, this all works correctly. It appears like so:

correct position

In iOS 8, this does not work correctly. The contentView appears in completely the wrong position. Like so:

incorrect position

I have no idea why it's different in iOS 8. I would love some help figuring out this issue!


Solution

  • I have found the answer!

    Apparently in iOS 7, it assumes the correct constraints for placing the contentView inside the CNJobMapView. In iOS 8, this is no longer the case. I have modified the awakeFromNib function as follows:

    -(void)awakeFromNib {
      [[NSBundle mainBundle] loadNibNamed:@"CNJobMapView" owner:self options:nil];
      [self addSubview: self.contentView];
      [self internalSetup];
    
      NSDictionary *views = NSDictionaryOfVariableBindings(contentView);
      NSArray *horizContentConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView]|" options:0 metrics:nil views:views];
      [self addConstraints:horizContentConstraints];
      NSArray *vertContentConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]|" options:0 metrics:nil views:views];
      [self addConstraints:vertContentConstraints];
    }
    

    And the problem is now fixed.