7

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?

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132
  • I have not actually filed a Radar for it yet, but I've run into this as well and it seems to be an iOS 6 bug. Creating the UIBarButtonItem and its view programmatically exhibits the same problem. – Ryan Aug 12 '13 at 16:07
  • Did you find a solution for this issue ? – Redwarp Apr 07 '14 at 09:23
  • Any news on that topic? I think I still have a similar issue (albeit with a toolbar) in iOS 7. – Joachim Kurz Jul 08 '14 at 08:55

1 Answers1

1

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.

Community
  • 1
  • 1