为什么单击取消按钮后,我的searchBar不能重置为初始状态?

时间:2019-09-16 07:48:53

标签: swift

我有一个带有取消按钮的 searchBar 。当我单击“取消”按钮时,它不会将 searchBar 重置为其初始状态。

Here是完整的源代码。


var searchBar: UISearchBar = UISearchBar()

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

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.text = nil
        searchBar.setShowsCancelButton(false, animated: true)
        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 更改为其初始状态?现在,在用户单击“取消”后,它将 searchText 更改为 nil

2 个答案:

答案 0 :(得分:1)

searchBarCancelButtonClicked函数中:

searchBar.text = ""
searchBar.showsCancelButton = false

也在textDidChange中:

yourSearchBar.showsCancelButton = true

答案 1 :(得分:0)

我认为是因为这段代码:

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(true, animated: true)
}

必须是:

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
}