如何访问轻按回调的搜索栏



我正在构建一个应用程序,我有一个搜索栏与表视图。但我不知道当用户点击搜索,去到不同视图控制器的数据有人能帮我吗?我的代码就像这样

@IBOutlet weak var textSearchBar: UITextField!
@IBOutlet weak var tableSearchResult: UITableView!
var fruitsArray:[String] = Array()
var searchedArray:[String] = Array()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

fruitsArray.append("Apple")
fruitsArray.append("Orange")
fruitsArray.append("Litch")
fruitsArray.append("Pineapple")

for str in fruitsArray {
searchedArray.append(str)
}
tableSearchResult.dataSource = self
textSearchBar.delegate = self
}
// Mark:- UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchedArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

}

cell?.textLabel?.text = searchedArray [indexPath.row]
return cell!
}
// MARK: - UITextFieldDelegate
func textFieldShouldClear(_ textField: UITextField) -> Bool {
textSearchBar.resignFirstResponder()
textSearchBar.text = ""
self.searchedArray.removeAll()
for str in fruitsArray {
searchedArray.append(str)
}
tableSearchResult.reloadData()
return true
}

Thank you Very Much

试试这个:

extension ViewController: UISearchBarDelegate {
func searchBar(
_ searchBar: UISearchBar,
textDidChange searchText: String
) {
// Here instructions for when searchBarText change 
}

func searchBarCancelButtonClicked(
_ searchBar: UISearchBar
) {
self.searchBar.endEditing(true)
}
}

最新更新