iOS11后用-initWithCustomView:创建UIBarButtonItem时,传统的使用方式也许会导致customView里的buttons无法点击的问题。这是由于iOS11之后导航栏的层级结构发生了很大的变化,新的层级结构如下图所示,
可以看到UINavigationBar不再直接组织barButtonItem和titleView,而是由_UINavigationBarContentView组织,而我们的leftBarButtonItem和rightBarButtonItem都是通过_UIButtonBarStackView间接显示在UINavigationBar上,而问题就出现在_UIButtonBarStackView这里。_UIButtonBarStackView显然是UIStackView的子类,布局时必然遵循UIStackView的布局原理。以下是摘自苹果官方的一段描述,
Stack View and Auto Layout
The stack viewuses Auto Layout to position and size its arranged views
. The stack view aligns the first and last arranged view with its edges along the stack’s axis. In a horizontal stack, this means the first arranged view’s leading edge is pinned to the stack’s leading edge, and the last arranged view’s trailing edge is pinned to the stack’s trailing edge. In vertical stacks, the top and bottom edges are pinned, to the stack’s top and bottom edges respectively. If you set the stack view’s layoutMarginsRelativeArrangement property to YES, the stack view pins its content to the relevant margin instead of its edge.For all distributions except the UIStackViewDistributionFillEqually distribution,the stack view uses each arranged view’s intrinsicContentSize property when calculating its size along the stack’s axis
. UIStackViewDistributionFillEqually resizes all the arranged views so they are the same size, filling the stack view along its axis. If possible, the stack view stretches all the arranged views to match the view with the longest intrinsic size along the stack’s axis.
从文中标红处我们能看出Stack View是采用Auto Layout
组织子视图的,而且Stack View内容大小也是依赖子视图的intrinsicContentSize
。在iOS11之前我们只要指定自定义视图的Size,barButtonItem就能正常显示和点击,而iOS11之后若不指定自定义视图的intrinsicContentSize,显示Stack View的height会为0,因而即使customView能正常显示也是不能点击的。