如何搜索键盘中的搜索按钮?

时间:2016-07-11 06:30:02

标签: ios swift uisearchcontroller

我的tableview标题中有一个搜索栏。为此,我正在使用uisearchcontroler。但是当我在搜索栏中发短信时它会更新tablview数据,我需要在点击键盘上的搜索按钮时更新tablview,因为我在api中获取搜索数据,每次当我在搜索栏中发短信时它都会请求并且需要很长时间。我怎么解决这个问题?

var resultSearchController = UISearchController()
var indicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
var ref=UIRefreshControl()
override func viewDidLoad() {
    super.viewDidLoad()


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

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    })()

    indicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    indicator.center = view.center
    view.addSubview(indicator)
    indicator.bringSubviewToFront(view)

    indicator.startAnimating()
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    getRequests.getType1(tableView,spinner: indicator)

    ref.addTarget(self, action: #selector(Catalog1TableViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
    ref.attributedTitle = NSAttributedString(string: "Загрузка")
    tableView.addSubview(ref)

}


func updateSearchResultsForSearchController(searchController: UISearchController)
{
    indicator.startAnimating()
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    tableView.reloadData()
    getRequests.getProduct(tableView, spinner: indicator,name: searchController.searchBar.text!)
    for item in getRequests.product {
        if item.productTitle.containsString(searchController.searchBar.text!){
            filteredTableData.append(item)
        }

    }
    tableView.reloadData()
}

2 个答案:

答案 0 :(得分:5)

尝试实现UISearchBar Delegate方法:

func searchBarSearchButtonClicked(searchBar: UISearchBar)

答案 1 :(得分:2)

您应该在视图控制器中实现类似的功能。

var resultSearchController = UISearchController()
resultSearchController.searchBar.delegate = self

extension ViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("search button click")
    } 
}