如何将搜索栏添加到导航栏

时间:2016-08-29 17:40:15

标签: ios swift ipad uikit uisearchcontroller

我希望将UISearchController管理的搜索栏添加到导航栏的右侧。

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    searchController.searchBar.placeholder = "Search"
    searchController.searchBar.searchBarStyle = .Minimal
    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200.0, height: 44.0)
    searchController.hidesNavigationBarDuringPresentation = false
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchController.searchBar)

当我点击搜索栏(因此它变为活动状态)时,它覆盖整个导航栏(同时重叠其他所有内容)而不是小部分。我该如何修复它的框架?

1 个答案:

答案 0 :(得分:3)

在UIView中包装搜索栏似乎可以解决问题。

    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200.0, height: 44.0)
    let barContainer = UIView(frame: searchController.searchBar.frame)
    barContainer.backgroundColor = UIColor.clearColor()
    barContainer.addSubview(searchController.searchBar)
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: barContainer)