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?
Looks like a duplicate of iOS Autolayout and UIToolbar/UIBarButtonItems
UIBarButtonItems
do not inherit from UIView
, so using auto-layout based custom views within them might not be fully supported. Sounds like you have to do the pre auto layout thing until the issue is resolved. I would suggest filing a bug.
EDIT: By the pre auto layout thing, I mean manipulating the frame of your views directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With