搜索时停用UIRefreshControl

时间:2018-04-07 13:15:56

标签: swift uisearchcontroller uirefreshcontrol

我在TableView上实现了一个UIRefreshControl,另外,我添加了一个带有searchBar的searchController。

搜索以及刷新工作完全没问题,我唯一挣扎的是如何停用"拉动刷新" searchController处于活动状态时的函数。

我尝试实施this解决方案,但不知怎的,这对我不起作用。

1 个答案:

答案 0 :(得分:4)

使您的viewcontroller符合UISearchBarDelegate

class ViewController: UIViewController, UISearchBarDelegate

并实现其两个方法

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    self.removeRefreshControl()        
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    self.initRefreshControl()
}

在每个方法中调用函数来设置和删除UIRefreshControl

func initRefreshControl() {
    self.refreshControl = UIRefreshControl()
    self.refreshControl?.addTarget(self, action: #selector(ViewController.refreshData), for: .valueChanged)

    self.tableView.refreshControl = self.refreshControl
}

func removeRefreshControl() {
    self.refreshControl = nil
}

完整的代码是:

class ViewController: UIViewController, UISearchBarDelegate {

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    var refreshControl: UIRefreshControl?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.initRefreshControl()
    }

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.removeRefreshControl()
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.initRefreshControl()
    }

    func initRefreshControl() {
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.addTarget(self, action: #selector(ViewController.refreshData), for: .valueChanged)

        self.tableView.refreshControl = self.refreshControl
    }

    func removeRefreshControl() {
        self.refreshControl = nil
    }

    @objc func refreshData() {
        ....
        ....
        self.refreshControl?.endRefreshing()
    }
}

这应该有用。