以编程方式添加UITableView后UISearchBar不显示的问题如何解决
问题原因及修复方案
核心原因
- 你的tableView顶部约束直接绑定了
view.topAnchor,没有适配导航栏安全区域,tableView会直接覆盖搜索栏的显示位置 navigationItem.hidesSearchBarWhenScrolling默认值为true,页面首次加载时搜索栏默认会被收起,容易被误判为无法显示- 缺少
UISearchController的基础显示配置,可能导致层级异常
修复代码
只需要修改configureTableView方法里的顶部约束,以及补充viewDidLoad里的搜索栏配置即可,修改后的完整代码如下:
import UIKit class SearchResultsViewController: UIViewController { let searchController = UISearchController(searchResultsController: nil) let reuseIdentifier = "ResultCell" var tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Search" configureTableView() // 补充搜索栏配置 navigationItem.searchController = searchController // 页面加载时默认显示搜索栏 navigationItem.hidesSearchBarWhenScrolling = false searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.delegate = self } func configureTableView() { view.addSubview(tableView) tableView.rowHeight = view.frame.height * 0.15 tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true // 修改顶部约束为安全区域顶部,避免覆盖导航栏及搜索栏 tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true } } // MARK: - Search Bar Delegate extension SearchResultsViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print(searchBar.text!) } } extension SearchResultsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) // 可自行修改为实际业务内容 cell.textLabel?.text = "测试条目 \(indexPath.row + 1)" return cell } }
内容的提问来源于stack exchange,提问作者adp2013
相关产品推荐
相关产品推荐

