我的谜题是“为什么iOS 11Custom UINavigationItem titleView和leftBarButtonItem与iOS9不同?”。
当我在HomeViewController的navigationItem中自定义titleView和leftBarButtonItem时,我发现了一些不同的东西。
以下代码成功将自定义leftBarButtonItem和自定义titleView放置在导航栏中。
// customize leftBarButtonItem
_customLeftItemView.frame = CGRectMake(0, 0, 60, 40);
UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLeftItemAction:)];
[_customLeftItemView addGestureRecognizer:tapGes];
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:_customLeftItemView];
leftItem.width = 60.0f;
self.navigationItem.leftBarButtonItem = leftItem;
// customize titleView
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 250, 40)];
searchBar.placeholder = @"Please search address";
searchBar.delegate = self;
self.navigationItem.titleView = searchBar;
_customLeftItemView
如下图所示。customLeftItemView In Storyboard
在执行的代码之上,iOS11和iOS9之间的外观差异,如下图所示。iPod Simulator iPhone8 iOS11
当我通过调试视图层次结构工具检查差异时,我发现searchBar
占据了UINavigationBarContentView
右侧的UISearchBarTextField
和UIButtonBarStackView
的整个区域。应用程序在iPhone 8中运行。但是,当App在iPod(iOS 9)中运行时,searchBar
没有占据UINavigationBarContentView
的整个区域,它位于UIButtonBarStackView
的右侧。代码_customLeftItemView.frame = CGRectMake(0, 0, 60, 40);
在iOS9中有效,因此leftBarButtonItem宽度是固定的,如果在iOS11中运行,则会失效。差异如下图所示。iPod Debug View Hierarchy iPhone8 Debug View Hirarchy