如何从 table 视图中显示的搜索结果导航到另一个视图?

How do i navigate to another view from search results displayed in table view?

下面的代码是我的viewController代码。 json 文件中的单词会显示在 table 视图中,单击某个单词会转到显示与该单词关联的元素的另一个页面。但是,当搜索结果显示在 table 视图中时,我无法导航到该页面。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating{

@IBOutlet weak var mainTableView: UITableView!

var words = [wordStats]()
var filteredArray = [wordStats]()
var searchController = UISearchController()
var resultsController = UITableViewController()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    getJson {
        self.mainTableView.reloadData()
    }

    mainTableView.delegate = self
    mainTableView.dataSource = self

    searchController = UISearchController(searchResultsController: resultsController)
    mainTableView.tableHeaderView = searchController.searchBar
    searchController.searchResultsUpdater = self

    resultsController.tableView.delegate = self
    resultsController.tableView.dataSource = self

}

func updateSearchResults(for searchController: UISearchController) {
    filteredArray = words.filter({ (words: wordStats) -> Bool in
        if words.word.contains(searchController.searchBar.text!){
            return true
        }else{
            return false
        }
    })
    resultsController.tableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == resultsController.tableView{
        return filteredArray.count
    }else{
        return words.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
    if tableView == resultsController.tableView{
        cell.textLabel?.text = filteredArray[indexPath.row].word.capitalized
    }else{
        cell.textLabel?.text = words[indexPath.row].word.capitalized
    }
    //cell.textLabel?.text = words[indexPath.row].word.capitalized
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "wordDetails", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? HeroViewController{
            destination.word = words[(mainTableView.indexPathForSelectedRow?.row)!]
        }
}

func getJson(completed: @escaping () -> ()){
    let path = Bundle.main.path(forResource: "week_14", ofType: "json")
    let url = URL(fileURLWithPath: path!)
    let data = try! Data(contentsOf: url)
            do {
                self.words = try JSONDecoder().decode([wordStats].self, from: data)
                DispatchQueue.main.async{
                    completed()
                }
            }catch{
                print("JSON error")
            }
}

}

最初从 JSON 文件中获取数据后,数据显示在 mainTableView 中,但在我单击该项目时搜索后,应用程序崩溃了。有人可以帮我吗?

struct wordStats:Decodable{
let word: String
let synonym: String
let meaning: String
let example: String
let video: String

}

这是 wordStats

Post 崩溃日志。根据我们所掌握的信息,我的猜测是您在 prepareForSegue 中崩溃了:

destination.word = words[(mainTableView.indexPathForSelectedRow?.row)!]

可能是使用筛选结果时出现索引错误。这可能会解决它:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? HeroViewController{

            if tableView == resultsController.tableView {
                destination.word = filteredArray[(mainTableView.indexPathForSelectedRow?.row)!]
            } else {
                destination.word = words[(mainTableView.indexPathForSelectedRow?.row)!]
            }
        }
}

这就是最终起作用的方法

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? HeroViewController {
        if let indexPath = mainTableView.indexPathForSelectedRow{
            if isFiltering(){
                destination.word = filteredArray[indexPath.row]
            }else{
                destination.word = words[indexPath.row]
            }
        }
    }
}