【问题标题】:Place UISearchBar above tableview but not in tableview or navbar将 UISearchBar 放在 tableview 上方但不在 tableview 或导航栏中
【发布时间】:2015-12-22 23:15:40
【问题描述】:

我的故事板中的视图控制器上有一个 UISearchBar 和一个 UITableView。搜索栏位于 tableview 上方,因此它不会滚动。我的问题是 UISearchController 的初始化创建了自己的 SearchBar 实例,该实例与我手动添加并定位在情节提要上的实例不同。

如何将我的故事板 SearchBar 设置为我的 UISearchController 为我创建的?

class ITSearchController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

    // So that the search results are displayed in the current controllers table view
    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

        // This didn't work
        //var view = self.view.viewWithTag(777)
        //view = searchController.searchBar

        // This works but isn't what I want
        //tableView.tableHeaderView = searchController.searchBar

        // This works but places it in the nav section. Not what I want.
        // self.navigationItem.titleView = searchController.searchBar

        // This is what I want but doesn't work. Basically make the search bar on my storyboard equal to the one created.
        searchBar = searchController.searchBar

    }
}

【问题讨论】:

    标签: ios swift uisearchbar uisearchcontroller


    【解决方案1】:

    你不能使用 UISearchController 放置在情节提要上的搜索栏,因为 UISearchController 提供了自己的情节提要。

    或者,将情节提要中的搜索栏替换为UIView,然后将UISearchController 提供的搜索栏作为子视图添加到UIView

    class ITSearchController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchView: UIView! // make this UIView
    
    // So that the search results are displayed in the current controllers table view
    let searchController = UISearchController(searchResultsController: nil)
    
    override func viewDidLoad() {
    
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true
    
        // This should work
        searchView.addSubview(searchController.searchBar)
    
    }
    }
    

    这会给你同样的行为。

    【讨论】:

    • 谢谢,这是我使用的解决方案。似乎您应该能够通过构造函数指定现有的 SearchBar 。我猜故事板的魔法总要在某个地方结束……
    猜你喜欢
    • 2019-06-13
    • 2016-04-06
    • 2018-04-30
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多