如何使 UISearchController() 默认隐藏?

Posted

技术标签:

【中文标题】如何使 UISearchController() 默认隐藏?【英文标题】:how to make the UISearchController() hidden by default? 【发布时间】:2015-11-07 22:43:32 【问题描述】:

我已将 UISearchController() 添加到我的 UIViewController 中,如下所示:

class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating   

let tableData = ["Here's", "to", "the", "crazy"]
var filteredTableData = [String]()
var resultSearchController = UISearchController()

@IBOutlet var tableView: UITableView!


override func viewDidLoad() 
    super.viewDidLoad()

    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.resultSearchController = (
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    )()

    // Reload the table
    self.tableView.reloadData()

... 表视图函数 ...

func updateSearchResultsForSearchController(searchController: UISearchController)
    
        filteredTableData.removeAll(keepCapacity: false)

        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
        let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
        filteredTableData = array as! [String]

        self.tableView.reloadData()
    

我试图使搜索栏默认隐藏,换句话说,使其类似于“Notes”iPhone 应用程序的搜索栏样式,您必须向下滚动 tableView 才能显示搜索栏。有没有办法可以做到这一点?就像添加一个负约束,使其在 ViewController 加载时隐藏在导航栏下?

【问题讨论】:

***.com/a/31595116/4475605 【参考方案1】:

找到了一个很简单的默认隐藏搜索栏的解决方案,我找到了答案here

我只需要在 viewDidLoad() 中添加这一行:

tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)

更新为 Swift 3.0 语法:

tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)

【讨论】:

您可以补充说,只有在第一部分至少有一行的情况下才应该发出此命令。

以上是关于如何使 UISearchController() 默认隐藏?的主要内容,如果未能解决你的问题,请参考以下文章

UISearchController 使 UITableView 的内容变黑

使 UISearchController 搜索栏自动激活

UISearchController 使控制器变黑

聚焦时如何调整 UISearchController.searchBar 的大小问题?

如何使 UITableViewController 符合协议 UISearchResultsUpdating?

以编程方式显示 UISearchController 的搜索栏