【问题标题】:searchBar in titleView of navigationItem disappears while app goes to background当应用程序进入后台时,navigationItem 的 titleView 中的 searchBar 消失
【发布时间】:2019-11-26 11:41:59
【问题描述】:
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

storyboard 设计中的导航栏有搜索栏,在推送 viewController 时隐藏,storyboard 设计中的导航栏在展示 VC 时显示。推VC时,设置同一个搜索栏为

self.navigationItem.titleView = searchBar

也试过了,

navigationController?.navigationBar.topItem?.titleView = searchBar

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

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    UISearchController 用于UISearchBar。喜欢,

    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
        }
    }
    

    您可以获取更多信息here

    我希望这会对你有所帮助。

    【讨论】:

    • 谢谢您的回答。但同样的问题。当我返回应用程序时,搜索栏实际上出现在导航栏中。我可以在 searchBar 中编辑和搜索,但它不可见。
    • 您可以按照我在答案中添加的链接在导航栏中添加搜索栏。如果没有解决,您可能会解决您的问题,那么这不是搜索栏问题。您必须调试另一个问题。 @Kamalraj
    猜你喜欢
    • 2011-05-22
    • 2012-09-12
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多