Swift:如何访问所选 table 视图单元格的值

Swift: How to access value of selected table view cells

如何访问用户选择的 table 视图的单元格值?如果用户没有搜索,我知道如何访问该值,因为我只能访问数组的 IndexPath 值,但是当用户搜索了某些内容时,我不能访问,因为 townArray 不会与搜索的单元格对齐显示。

为了让您更好地理解 - 就说我有一系列水果,其中有 [苹果、香蕉、橙子]。如果用户搜索香蕉,那么唯一显示文本(结果)的单元格将显示香蕉。如果我随后尝试访问 fruits 的 IndexPath 元素,我将获得 apples,因为它是 fruits 的第一个元素,而 bananas 是第一个显示的元素。我想要的是在用户选择香蕉并搜索 "bananas" 而不是苹果时访问值香蕉。我知道这可能令人困惑,但如果您对我如何解决此问题有任何想法,请告诉我。

var searchedResult: [Fruit] = yourSearchingFunction()
tableview.reloadData()

在 TableView 重新加载新的水果集合后,IndexPaths 会正确刷新

解释如下代码所示:

class ViewController: UIViewController {

    @IBOutlet private weak var tableView: UITableView!
    private var originalFruits: [Fruit] = [] // This data is used to cache
    private var fruits: [Fruit] = [] //  This data is used to display on TableView

    // MARK: - View Cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        setupTableView()
        setupData()
    }

    private func setupData() {
        // Loading all fruits at the first time [Apple, Banana, Orange ]
        originalFruits = yourSetupDataFunctionToFetchAllFruitsAtTheFirstTime() 
        fruits = originalFruits
        tableView.reloadData()
    }

    @IBAction private func actionTapToSearchButton(_ sender: Any) {
        let searchingKey = searchTextField.text
        if searchingKey.isEmpty {
            fruits = originalFruits
        } else {
            fruits = yourSeacrchingFruitFunction(searchingKey)
        } 
        tableView.reloadData()
    }
}

// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: FruitCell.identifier) as? FruitCell {
            return cell
        }
        return UITableViewCell()
    }
}

// MARK: - UITableViewDelegate
extension ViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
}