【问题标题】:IOS: UISearchBar partly covering UINavigationBar with promptIOS:UISearchBar 部分覆盖 UINavigationBar 提示
【发布时间】:2026-01-14 20:45:01
【问题描述】:

我正在使用带有 UISearchBar 的 UITableViewController。 UITableViewController 嵌入在 UINavigationController 中。当表格视图显示时,搜索栏按预期位于顶部(导航栏下方)。导航栏显示标题和提示。

当我单击搜索栏时,它会向上移动并隐藏导航栏中的标题。提示仍然可见。 不使用提示时,点击后搜索栏仍按预期在导航栏下方。

我创建了一个非常简单的项目来演示我的问题。该项目具有以下 UITableViewController 文件:

import UIKit

class searchTVC: UITableViewController, UISearchControllerDelegate, UISearchResultsUpdating {
    fileprivate let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Title"
        navigationItem.prompt = "prompt"

        tableView.backgroundColor = UIColor.gray

        // Add search bar
        searchController.delegate = self
        searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()

        tableView.tableHeaderView = searchController.searchBar

        // remove separators for empty table
        tableView.tableFooterView = UIView()
    }

    func updateSearchResults(for searchController: UISearchController) {
        // ignore
    }
}

在故事板中,只有一个空的 UITableViewController 嵌入在 UINavigationController 中。结果如下所示。

如果您注释掉设置提示的行,则行为符合预期。

我最近将我的代码更新到了 Swift 4。我不记得我在使用 Swift 3 时看到过这种行为,但我不完全确定它是在 Swift 4 中引入的。

我是在代码中遗漏了什么还是这是一个错误?

【问题讨论】:

    标签: ios uinavigationbar uisearchbar prompt swift4


    【解决方案1】:

    将这些设置在viewDidLoad:

    self.definesPresentationContext = true
    self.edgesForExtendedLayout = .bottom
    

    【讨论】: