为什么单击取消按钮后,表格视图不重置结果?

时间:2019-09-16 09:23:51

标签: swift

当用户在 searchBar 中键入内容时,结果将在我的 tableView 中更新。当用户取消 searchBar 中的搜索时,结果将重置。但是,当用户想要取消搜索栏之外的搜索时, tableView 不会重置,而是保留输入。 我做了gif来说明我的问题。

here是该类的完整源代码。


var searchBar: UISearchBar = UISearchBar()

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchBarText = searchBar.text?.lowercased()
        searchBarScope = searchBar.selectedScopeButtonIndex
        self.searchBar.showsCancelButton = true
        showList()
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.searchBar.showsScopeBar = false
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.text = ""
        self.searchBar.showsCancelButton = false
        self.searchBar.endEditing(true)
    }

    public func setupSearchBarStyle() {
        UISearchBar.appearance().searchBarStyle = .minimal
        UISearchBar.appearance().backgroundColor = UIColor.white
        UISearchBar.appearance().barTintColor = UIColor.white
    }

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchBar.showsScopeBar = true
        if (navigationItem.title != nil) {
            self.searchBar.scopeButtonTitles = [String(format: "gesamte %@", ci("project_s")),  String(format: "in %@", navigationItem.title!)]
        }
    }

    override func viewDidLayoutSubviews() {
        self.searchBar.sizeToFit()
    }

    public override func viewDidLoad() {

        self.navigationController?.setNavigationBarHidden(false, animated: false)


        navigationItem.title = navigationItem.title ?? ci("plan_p")

        guard let projectId = GlobalState.selectedProjectId, let byProject : Results<Structure> = self.by(projectId: projectId) else {
            return
        }

        //search bar
        tableView.rowHeight = 100.0
        tableView.tableHeaderView = searchBar

        self.searchBar.showsCancelButton = true
        self.searchBar.sizeToFit()
        self.definesPresentationContext = true
        self.searchBar.delegate = self

        tableView.allowsMultipleSelectionDuringEditing = true

当用户取消 searchBar 之外的搜索时,应重置表格视图。

1 个答案:

答案 0 :(得分:0)

我不知道这是否是您要寻找的东西。但是,如果您想在用户触摸searchBar以外的地方时重置数据,可以尝试一下。

    func resetData()
    {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(loadData))

        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func loadData()
    {
        //The code to reset
    }

也在您的viewDidLoad()中:resetData()

但是我不认为这是正确的方法。如果用户点击,此代码将执行某些操作。我认为,如果用户这样做,您不想重设数据。