iOS 10`rightBarButtonItem`移动到导航栏

时间:2018-01-05 18:06:56

标签: ios objective-c uinavigationbar uisearchcontroller

在我的视图控制器中,我在导航栏中显示搜索控制器。

/*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中,排序按钮位于导航栏内搜索控制器的旁边,如下所示: enter image description here

但是,在iOS 10中,按钮完全移出导航栏: enter image description here

我的第一个想法是限制willLayoutSubviews中的按钮,但由于按钮没有view组件,我无法将translatesAutoresizingMaskIntoConstraints设置为NO然后我通过完全删除搜索控制器来检查是否存在将搜索控制器放入导航栏的问题。仍然(在iOS 10中)按钮位于导航栏之外: enter image description here

如何将rightBarButtonItem修复为iOS 10及更早版本的导航栏

1 个答案:

答案 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!