(Swift) 即使没有文本,如何在 searchBar 上显示取消按钮?
(Swift) How to show Cancel button on searchBar even if there is no text?
我有一个带有 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()
}
你可以尝试委托方法
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
和
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
我有一个带有 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()
}
你可以尝试委托方法
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
和
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}