在我的视图控制器中,我在导航栏中显示搜索控制器。
/*set appearance of search controller */
_searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
_searchController.searchBar.delegate = self;
_searchController.searchResultsUpdater = self;
[_searchController.searchBar sizeToFit];
_searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
_searchController.hidesNavigationBarDuringPresentation = NO;
_searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
我还在rightBarButtonItem
的帮助下创建了一个排序按钮。
/*add drop down sort menu button to navigation bar */
[self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];
self.navigationController.navigationBar.translucent = NO;
self.navigationItem.titleView = self.searchController.searchBar;
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
style:UIBarButtonItemStyleDone
target:self
action:@selector(displaySortMenu:)];
self.navigationItem.rightBarButtonItem = rightButtonItem;
rightButtonItem.image = [UIImage imageNamed:@"Sort"];
self.navigationItem.rightBarButtonItem.imageInsets = UIEdgeInsetsMake(6, 0, 0, 0);
在iOS 11中,排序按钮位于导航栏内搜索控制器的旁边,如下所示:
我的第一个想法是限制willLayoutSubviews
中的按钮,但由于按钮没有view
组件,我无法将translatesAutoresizingMaskIntoConstraints
设置为NO
。 然后我通过完全删除搜索控制器来检查是否存在将搜索控制器放入导航栏的问题。仍然(在iOS 10中)按钮位于导航栏之外:
如何将rightBarButtonItem
修复为iOS 10及更早版本的导航栏?
答案 0 :(得分:0)
我需要释放我为其创建的原始按钮才能正确地保留在导航栏中作为条形按钮项。
[self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];
self.navigationController.navigationBar.translucent = NO;
self.navigationItem.titleView = self.searchController.searchBar;
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
style:UIBarButtonItemStyleDone
target:self
action:@selector(displaySortMenu:)];
rightButtonItem.image = [UIImage imageNamed:@"Sort"];
self.navigationItem.rightBarButtonItem = rightButtonItem;
[rightButtonItem release]; // <-- this is the new line!