Auto Layout with UINavigationBar and UIBarButtonIt

2019-04-25 01:16发布

问题:

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?

回答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.