Swift - 使用搜索栏后出现结果错误

时间:2018-04-28 06:54:50

标签: swift xcode uisearchbar

我的搜索栏有点问题。如你在屏幕上看到的那样。当我没有过滤任何东西而我先点击它时,它会显示我的第一个细节屏幕,当我点击第二个时,它会显示第二个带有细节的屏幕,但是当我过滤某些内容时(例如在上一个屏幕中)并点击结果,它显示我的第一个屏幕,这是错误的,我想看到第二个屏幕的细节。我的代码在这里:

import UIKit

    //array definiton
    var names = [String]()
    var namesDesc = [String]()
    var namesDescWhereTo = [String]()
    var imageArr = [UIImage(named: "Alobal")!,UIImage(named: "Akumulátory")!,UIImage(named: "Akvária")!,UIImage(named: "Autovrak")!,UIImage(named:                  "Autosklo")!]
    var myIndex = 0


class mainTableViewController: UITableViewController, UISearchResultsUpdating {

    //definition variables for VC
    var namesTableView = names
    var filteredNames = [String]()
    var searchController : UISearchController!
    var resultsController = UITableViewController()


    override func viewDidLoad() {
        super.viewDidLoad()

        //load file with names - names.txt
        do {
            //definice názvu souboru + oddělovače
            if let path = Bundle.main.path(forResource: "names", ofType: "txt"){
                let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
                names = data.components(separatedBy: "\n")
            }
        } catch let err as NSError {
            //pokud je nějaký error
            print(err)
        }

        //load file with descriptions - namesDesc.txt
        do {
            //definice názvu souboru + oddělovače
            if let path = Bundle.main.path(forResource: "namesDesc", ofType: "txt"){
                let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
                namesDesc = data.components(separatedBy: "\n")
            }
        } catch let err as NSError {
            //pokud je nějaký error
            print(err)
        }

        //load file with information "where to" - namesDescWhereTo.txt
        do {
            //definice názvu souboru + oddělovače
            if let path = Bundle.main.path(forResource: "namesDescWhereTo", ofType: "txt"){
                let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
                namesDescWhereTo = data.components(separatedBy: "\n")
            }
        } catch let err as NSError {
            //pokud je nějaký error
            print(err)
        }


        namesTableView = names

        //definiton main title + call method setupNavBar()
        self.title = "Where to?"
        setupNavBar()


        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self
        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = self.searchController.searchBar
        self.searchController.searchResultsUpdater = self
        self.searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

    }



    //method where I define large titles
    func setupNavBar() {
        navigationController?.navigationBar.prefersLargeTitles = true

    }

    func updateSearchResults(for searchController: UISearchController) {
        self.filteredNames = self.namesTableView.filter { (name:String) -> Bool in
            if name.lowercased().contains(self.searchController.searchBar.text!.lowercased()) {
                return true
            } else {
                return false
            }
        }
        //reloading
        self.resultsController.tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.tableView {
            return self.namesTableView.count
        } else {
            return self.filteredNames.count
        }
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        if tableView == self.tableView {
            cell.textLabel?.text = self.namesTableView[indexPath.row]
        } else {
            cell.textLabel?.text = self.filteredNames[indexPath.row]
        }
            return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
        }

    }

main screen

If I click first

If I click second

If I search second and click on result, it shows me first page

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

在所有其他数据源方法(cellForRownumberOfRows等)中,您执行了此操作:

if tableView == self.tableView {
    // use the normal data source array
} else {
    // use the filtered data source array
}

那么为什么不在prepareForSegue中执行此操作,将myIndex对应的项目传递给下一个控制器?

您没有tableView的实例,因此您无法检查用户是否正在搜索,是吗?

除了检查传入的表视图是否是原始表视图外,您还可以检查isActive的{​​{1}}属性:

searchController

答案 1 :(得分:0)

@Sweeper我添加了prepareForSegue,但问题是一样的:(在目标VC中过滤后我看不到正确的结果。这个我添加到主VC。

override func prepare(
for segue: UIStoryboardSegue, sender: Any ? ) {
if segue.identifier == "segue" {
    if let indexPath = tableView.indexPathForSelectedRow {
        let resultName: String
        if isFiltering() {
            resultName = filteredNames[indexPath.row]
        } else {
            resultName = namesTableView[indexPath.row]
        }
        let controller = segue.destination as!ViewController
        controller.test = resultName
    }
}}

这是我在viewDidLoad()中的目的地VC:

title = test
recLabelDesc.text = test