UISearchController在ViewController中无法正常显示问题求助
问题根因及修复步骤
1. 首要必改错误
- 删掉
viewDidLoad里的self.view.addSubview(search.view)代码:UISearchController赋值给navigationItem.searchController后,会由导航栏自动管理布局展示,手动添加search.view会触发视图层级冲突,直接导致搜索栏无法正常渲染。
2. 检查导航控制器层级
- 确保你的
ContactListParent控制器是被包裹在UINavigationController中作为根视图或者栈内视图的,如果当前控制器没有处于导航栈内,navigationItem的所有配置(包括搜索栏)都不会生效。 - 额外检查是否有手动隐藏导航栏的代码,比如
navigationController?.setNavigationBarHidden(true, animated: false),如果有需要改成false,或者调整为你需要的显示模式。
3. 规范UISearchController初始化
你当前使用的无参数初始化方式已经废弃,建议替换为指定构造器:
// 如果你不需要单独的搜索结果展示控制器,就传nil,直接在当前页面展示结果 let search = UISearchController(searchResultsController: nil)
4. 可选:范围栏强制显示配置
如果修复后范围栏还是不显示,可以在initSearchCont方法末尾添加一行代码强制显示范围栏:
search.searchBar.showsScopeBar = true
备选方案:自定义位置放置搜索栏
如果你不需要将搜索栏放在导航栏内,而是要放在页面自定义位置,可以删掉navigationItem.searchController = search相关配置,直接将searchBar添加到当前视图即可:
// 放在initSearchCont方法末尾即可,frame可以根据你的需求调整 search.searchBar.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: view.bounds.width, height: 100) view.addSubview(search.searchBar)
修改后完整参考代码
类与变量定义
class ContactListParent:UIViewController, UISearchResultsUpdating, UISearchBarDelegate { // 替换原有初始化方式 let search = UISearchController(searchResultsController: nil) // 其他原有变量定义... }
初始化方法
func initSearchCont(){ search.searchResultsUpdater = self search.obscuresBackgroundDuringPresentation = false search.searchBar.enablesReturnKeyAutomatically = false search.searchBar.returnKeyType = .done definesPresentationContext = true navigationItem.searchController = search navigationItem.hidesSearchBarWhenScrolling = false search.searchBar.scopeButtonTitles = ["All", "Dogs", "Cats"] // 强制显示范围栏 search.searchBar.showsScopeBar = true search.searchBar.delegate = self }
viewDidLoad生命周期方法
override func viewDidLoad() { super.viewDidLoad() initArr() initSearchCont() // 已删除错误的self.view.addSubview(search.view)代码 let layout = UICollectionViewFlowLayout() contVC = ContactVC(collectionViewLayout: layout) contVC?.CLV = self self.addChild(contVC!) contVC?.view.frame = CGRect(x: 0, y: view.bounds.height*0.2, width: view.bounds.width, height: view.bounds.height) self.view.addSubview(contVC!.view) contVC?.didMove(toParent: self) }
内容的提问来源于stack exchange,提问作者Camille Basbous
相关产品推荐
相关产品推荐

