Joh*_*Doe 19 uisearchbar ios swift
我有一个带取消按钮的搜索栏.但是,当我单击"取消"按钮时,它不会关闭搜索栏.如何点击取消它会将搜索栏返回到第一个状态?
如果您有任何问题 - 请问我
Pet*_*odd 47
您需要实现UISearchBarDelegate:
class ViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
Run Code Online (Sandbox Code Playgroud)
将搜索栏委托设置为self
override func viewDidLoad() {
super.viewDidLoad()
searchBar.showsCancelButton = true
searchBar.delegate = self
Run Code Online (Sandbox Code Playgroud)
然后实现butCancelSearchAction委托函数,以执行取消搜索操作和重置搜索文本所需的任何操作:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// Do some search stuff
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Stop doing the search stuff
// and clear the text in the search bar
searchBar.text = ""
// Hide the cancel button
searchBar.showsCancelButton = false
// You could also change the position, frame etc of the searchBar
}
Run Code Online (Sandbox Code Playgroud)
ora*_*ako 11
class MyController: UIViewController, UISearchBarDelegate {
// Called when search bar obtains focus. I.e., user taps
// on the search bar to enter text.
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.text = nil
searchBar.showsCancelButton = false
// Remove focus from the search bar.
searchBar.endEditing(true)
// Perform any necessary work. E.g., repopulating a table view
// if the search bar performs filtering.
}
}
Run Code Online (Sandbox Code Playgroud)
尝试.它工作正常.
class MyViewController: UIViewController, UISearchBarDelegate {
func searchBarTextDidBeginEditing(_searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
//write other necessary statements
}
func searchBarCancelButtonClicked(_searchBar: UISearchBar) {
searchBar.text = nil
searchBar.setShowsCancelButton(false, animated: true)
// Remove focus from the search bar.
searchBar.endEditing(true)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44815 次 |
| 最近记录: |