swift - 如何以编程方式从搜索栏切换到显示屏幕
问题描述
所以我最近使用 tableview 和导航控件以编程方式编写了一个搜索栏。现在,在用户单击搜索栏中的某个项目后,我无法找到有关如何对搜索栏进行 segue 的信息。
我曾尝试使用视图控制器,但没有奏效。我认为我最好的选择是以编程方式进行。
编辑此代码中还没有实现显示屏的功能。我想知道单击搜索栏中的元素后需要什么代码(我是一个非常新的开发人员)才能进入另一个屏幕。有什么帮助!!***
import UIKit
class SearchTableViewController: UITableViewController, UISearchBarDelegate {
let searchBar = UISearchBar()
let tableData = ["Boston University", "Boston College", "Northeastern University", "Suffolk University", "American University", "Harvard University", "Massachusetts Institute of Technology", "Tufts University", "Berklee College of Music", "Emerson College"]
//variables added for search function
var filteredArray = [String()]
var shouldShowSearchResults = false
override func viewDidLoad() {
super.viewDidLoad()
createSearcherBar()
}
func createSearcherBar() {
searchBar.showsBookmarkButton = false
searchBar.placeholder = "Search College"
searchBar.delegate = self
self.navigationItem.titleView = searchBar
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredArray = tableData.filter({ (names: String) -> Bool in
return names.range(of: searchText, options: .caseInsensitive) != nil
})
if searchText != "" {
shouldShowSearchResults = true
self.tableView.reloadData()
}
else{
shouldShowSearchResults = false
self.tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if shouldShowSearchResults {
return filteredArray.count
}
else{
return tableData.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
if shouldShowSearchResults {
cell.textLabel!.text = filteredArray[indexPath.row]
return cell
}
else{
cell.textLabel!.text = tableData[indexPath.row]
return cell
}
}
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
shouldShowSearchResults = true
searchBar.endEditing(true)
self.tableView.reloadData()
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
希望我能让用户点击搜索栏中的一个选项,然后将他们带到不同的页面。
解决方案
首先,您的方法textDidChange
不必要地昂贵,因为即使搜索文本为空,您也总是在过滤数组。这个效率更高
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
shouldShowSearchResults = false
filteredArray.removeAll() // good practice to release memory when the search is finished
} else {
filteredArray = tableData.filter{ $0.range(of: searchText, options: .caseInsensitive) != nil }
shouldShowSearchResults = true
}
self.tableView.reloadData()
}
其次,声明filteredArray
略有错误。括号必须在括号之外。您的语法声明了一个包含一个空字符串的字符串数组。
var filteredArray = [String]()
要回答您的问题,请实施didSelectRowAt
并添加相同的shouldShowSearchResults
逻辑来区分数组。调用performSegue
并将字符串传递为sender
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = shouldShowSearchResults ? filteredArray[indexPath.row] : tableData[indexPath.row]
performSegue(withIdentifier: "MyIdentifier", sender: item)
}
把它放进去prepare(for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "MyIdentifier" else { return }
let destinationController = segue.destination as! MyViewController
let item = sender as! String
...
推荐阅读
- ecmascript-6 - ES6 创建一个包含对的数组数组
- objective-c - 如何在 MacOS 中保持沙盒模式获得批准的同时获取用户的 IP 地址?
- angular - 在包装器中显示 Angular Material mat-error
- c# - .NET Azure 函数 - 如何从流中返回 JSON 对象?
- c++ - Visual Studio 2015:外部“C”和“export”关键字
- python - 如何在预测中返回多个项目?
- excel - Excel 2016 Power Query 无法加载到电子表格
- scala - 可以将 udf 包装器添加到此数据帧操作
- ruby-on-rails - Spree API 身份验证扩展不起作用
- hive - 如何在 NiFi 中使用 UDF?