首页 > 解决方案 > 如何以编程方式从搜索栏切换到显示屏幕

问题描述

所以我最近使用 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.
    }
    */

}

希望我能让用户点击搜索栏中的一个选项,然后将他们带到不同的页面。

标签: swiftxcode

解决方案


首先,您的方法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
    ...

推荐阅读