解決iOS11后UIBarButtonItem自定義視圖里的按鈕不響應點擊的問題
iOS11后用-initWithCustomView:創(chuàng)建UIBarButtonItem時,傳統(tǒng)的使用方式也許會導致customView里的buttons無法點擊的問題。這是由于iOS11之后導航欄的層級結構發(fā)生了很大的變化,新的層級結構如下圖所示,

可以看到UINavigationBar不再直接組織barButtonItem和titleView,而是由_UINavigationBarContentView組織,而我們的leftBarButtonItem和rightBarButtonItem都是通過_UIButtonBarStackView間接顯示在UINavigationBar上,而問題就出現(xiàn)在_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內(nèi)容大小也是依賴子視圖的intrinsicContentSize。在iOS11之前我們只要指定自定義視圖的Size,barButtonItem就能正常顯示和點擊,而iOS11之后若不指定自定義視圖的intrinsicContentSize,顯示Stack View的height會為0,因而即使customView能正常顯示也是不能點擊的。