在UISearchController swift 2.0上隐藏取消按钮

时间:2015-11-06 20:37:24

标签: ios swift search ios9 uisearchbar

theres是否可以隐藏UISearchController上的取消按钮? enter image description here

我想知道的其他行为是否可行,是用户按下取消按钮,在UISearchBar上设置文本。

由于

1 个答案:

答案 0 :(得分:-2)

使用seachController.searchBar.setShowsCancelButton(false,animated:false)似乎仍然没有这样做。

尝试将UISearchBarDelegate添加到您的控制器并将searchBar的委托分配给self。然后,您可以使用searchBarShouldBeginEditing来修改其可见性。

    import UIKit

    class TableViewController: UITableViewController, UISearchBarDelegate {

    var searchController: UISearchController!
    let menuItems: [String] = ["Row 1", "Row 2", "Row 3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier("SearchResultsViewControllerStoryboardIdentifier") as! SearchResultsTableViewController


        searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.searchBar.delegate = self
    }

    @IBAction func searchButtonPressed(sender: UIBarButtonItem) {
        presentViewController(searchController, animated: true, completion: nil)
    }

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        searchController.searchBar.setShowsCancelButton(false, animated: true)

        return true
    }

    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuItems.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        cell.textLabel?.text = self.menuItems[indexPath.row]

        return cell
    }
}