首页 > 解决方案 > 当应用程序进入后台时,navigationItem 的 titleView 中的 searchBar 消失

问题描述

lazy var searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 
self.view.bounds.width - 50, height: 30))

searchBar.delegate = self
searchBar.sizeToFit()
navigationBar.topItem?.titleView = searchBar

故事板设计中的导航栏有搜索栏,在推送viewController时隐藏,故事板设计上的导航栏在展示VC时显示。在推送 VC 时,将相同的搜索栏设置为

self.navigationItem.titleView = searchBar

也试过,

navigationController?.navigationBar.topItem?.titleView = searchBar

titleView 显示在 viewDidLoad() 和 viewDidAppear() 上,但是当进入后台并返回应用程序时,搜索栏会消失。

标签: iosswift

解决方案


Use UISearchController for UISearchBar. Like,

class ViewController: UITableViewController, UISearchResultsUpdating {

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        self.definesPresentationContext = true

        // Place the search bar in the navigation item's title view.
        self.navigationItem.titleView = searchController.searchBar

        // Don't hide the navigation bar because the search bar is in it.
        searchController.hidesNavigationBarDuringPresentation = false
    }
}

You can get more Information here.

I hope this will help you.


推荐阅读