I like to create my views as standalone Xib files then instantiate them and add as subviews.
So, when working with a UINavigationBar
, I expected to be able to do the same thing, first creating my custom view - from the Xib - then adding it as a custom view to the UIBarButtonItem
:
UIBarButtonItem *anItem = [[UIBarButtonItem alloc] initWithCustomView:_myCustomView];
Then adding to the nav bar:
self.navigationBar.topItem.rightBarButtonItems = @[ anItem, anotherItem ];
So far so good.
Now, _myCustomView
uses Auto Layout (AL) and I thought this would be no problem. Not the case. I've tried just about everything. Nothing has worked. I even tried adding the custom view as a subview of the controller that has the navigation bar. Thinking that as siblings in the view hierarchy, AL would treat it as a regular view outside the UINavigationBar
.
That didn't work either. The controller's updateViewConstraints
was called but never applied. The view's initial frame stayed at CGRectZero
. It's as if AL sees that the view is on top of a UINavigationBar
, even as a sibling, and decides it doesn't need laying out.
Of course, I've tried bringSubviewToFront
, translatesAutoresizingMaskIntoConstraintstranslatesAutoresizingMaskIntoConstraints
, and so on. The latter gave the lovely:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. MyNavigationBar's implementation of -layoutSubviews needs to call super.'
So, the question is, has anyone loaded a custom view with AL from a Xib, and successfully set this as a customView
on a UIBarButtonItem
? If so, how?