【问题标题】:SearchBar goes out of UINavigationItem frame when it is activeSearchBar 处于活动状态时会超出 UINavigationItem 框架
【发布时间】:2017-11-01 06:54:48
【问题描述】:

我将searchControllersearchBar 放在navigationItem 中作为titleView 如下:

self.navigationItem.titleView = self.searchController.searchBar;

虽然它在未选中时非常适合(取消项目未显示),但如果它成为第一响应者并且取消项目出现在searchBar 旁边,它会稍微滑到navigationItem 下方。你可以看到下面的结果:

我该如何解决这个问题?有解决办法吗?

【问题讨论】:

    标签: ios objective-c uinavigationitem uisearchcontroller titleview


    【解决方案1】:

    您应该使用self.navigationItem.searchController 而不是self.navigationItem.titleView

    self.navigationItem.searchController = self.searchController;
    

    在此处了解更多信息https://developer.apple.com/documentation/uikit/uinavigationitem/2897305-searchcontroller

    【讨论】:

    • 它只适用于 iOS 11
    • 它在导航栏下创建一个新行并在那里显示搜索栏。我必须在一行中显示退出和取消项目之间的 searchBar,如图所示。
    • 你是否尝试添加 self.definesPresentationContext = YES;
    • 还有一个,你可以试试我在这个问题上的回答stackoverflow.com/questions/46940042/…
    • @trungduc self.definesPresentationContext 不影响 searchBar 的位置。
    【解决方案2】:

    使用下面的代码

    if #available(iOS 11.0, *) {
         navigationItem.searchController = searchController
    } else {
         // Fallback on earlier versions
         navigationItem.titleView = searchController?.searchBar
    }
    

    【讨论】:

    • 请看我为 trungduc 写的评论。
    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2017-01-19
    • 2022-01-23
    相关资源
    最近更新 更多