【问题标题】:(Swift) How to show Cancel button on searchBar even if there is no text?(Swift)即使没有文本,如何在 searchBar 上显示取消按钮?
【发布时间】:2020-02-19 08:51:47
【问题描述】:

我有一个带有Cancel 按钮的搜索栏。仅当我开始在 searchBar 中输入文本时,才会出现取消按钮。
我想要的是在用户点击搜索栏的那一刻(当光标和键盘出现时)显示取消按钮。

代码:

let searchController = UISearchController(searchResultsController: nil)
    var isSearchBarEmpty: Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    var searching = false

searchBar 方法:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemGreen]
        UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)

        searching = true
        searchBar.showsCancelButton = true
        tableView.reloadData()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        searching = false
        self.searchBar.endEditing(true)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searching = false
        searchBar.text = nil
        searchBar.showsCancelButton = false
        searchBar.endEditing(true)
        tableView.reloadData()
    }

【问题讨论】:

    标签: ios swift uisearchbar


    【解决方案1】:

    你可以试试委托方法

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

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

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2013-10-30
      相关资源
      最近更新 更多