存储在数组中并显示在UITableView中的UISearchBar结果正在弄乱我的didSelectRowAt indexPath方法(Swift)

时间:2018-06-07 23:40:10

标签: arrays swift uitableview uisearchbar

我有一个UITableView,其中填充了titles数组中的项目,我进行了设置,以便在调用didSelectRowAt indexPath时,将一个名为arrayIndex的变量更改为indexPath,并更改下一个VC的内容。

因此,如果用户点击:

  • 第0行> VC将具有标题0,定义0和链接0
  • 第12行> VC将拥有Title 12,Definition 12和Link 12

我有一个搜索栏,但是将过滤后的结果存储在searchResults数组中,并将它们显示在tableView中。执行搜索时,数组索引将不再对应,因此如果搜索查询将tableview更改为

  • 第0行的标题4> VC将具有标题0,定义0和链接0
  • 第1行的标题5> VC将具有标题1,定义1和链接1
  • 第2行的标题18> VC将具有标题2,定义2和链接2

我理解为什么它没有按预期工作,但我不知道如何更新我的逻辑来解决它。思考?这是我的代码:

ListController:

import UIKit

var arrayIndex = 0 // is used in DefinitionController to determine which title/definition/link to show.
var isSearching = false

class ListController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {

    @IBOutlet var tableView: UITableView!
    @IBOutlet var searchBar: UISearchBar!

    // Search Delegate
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText == "" {
            isSearching = false
            tableView.reloadData()
        } else {
            isSearching = true
            searchResults = (titles.filter { $0.lowercased().contains(searchText.lowercased()) })
            tableView.reloadData()
        }
    }

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

        if isSearching == true {
            // code to run if searching is true
        } else {
            arrayIndex = indexPath.row // assigns the value of the selected tow to arrayIndex
        }

        performSegue(withIdentifier: "segue", sender: self)
        tableView.deselectRow(at: indexPath, animated: true)
    }

    // Table Data Source
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isSearching == true {
            return searchResults.count
        } else {
            return titles.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Cell Data Source
        let cell = UITableViewCell()

        if isSearching == true {
            cell.textLabel?.text = searchResults[indexPath.row]
        } else {
            cell.textLabel?.text = titles[indexPath.row]
        }

        // Cell Visual Formatting
        cell.backgroundColor = UIColor(red:0.05, green:0.05, blue:0.07, alpha:0)
        cell.textLabel?.textColor = UIColor.white
        cell.textLabel?.font = UIFont(name: "Raleway", size: 18)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator

//        if (cell.isSelected) {
//            cell.backgroundColor = UIColor.cyan
//        }else{
//            cell.backgroundColor = UIColor.blue
//        }

        return cell
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "\(titles.count) Definitions"

        // TextField Color Customization
        let searchBarStyle = searchBar.value(forKey: "searchField") as? UITextField
        searchBarStyle?.textColor = UIColor.white
        searchBarStyle?.backgroundColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:0.05)

    }   
}

定义控制器:

import UIKit

class DefinitionController: UIViewController {

    @IBOutlet var definitionTitle: UILabel!
    @IBOutlet var definitionBody: UILabel!
    @IBOutlet var definitionSources: UILabel!

    // Open link in Safari
    @objc func tapFunction(sender:UITapGestureRecognizer) {
        print("tap working")
        if let url = URL(string: "\(links[arrayIndex])") {
            UIApplication.shared.openURL(url)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        definitionTitle.text = titles[arrayIndex]
        definitionBody.text = definitions[arrayIndex]


        self.title = "" // Used to be \(titles[arrayIndex])

        // Sources Link
        let tap = UITapGestureRecognizer(target: self, action: #selector(DefinitionController.tapFunction))
        definitionSources.addGestureRecognizer(tap)

    }

}

2 个答案:

答案 0 :(得分:1)

尝试使用字典,其中键是您的标题,其值是包含定义和链接的字典,以及用于存储搜索结果的数组,即搜索的键。

var dictionary = ["title 0":["definition 0", "Link 0"], "title 1": ["definition 1", "Link 1"]]

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText == "" {
        isSearching = false
        tableView.reloadData()
    } else {
        isSearching = true
        for (key, value) in dictionary {
       if key==searchText{
       resultsArray.append(key)
}
}
        tableView.reloadData()
    }
}

现在当您点击List Controller中的单元格时,让它知道您要在下一个VC中初始化和加载哪个密钥的详细信息:

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 let DefinitionViewController = self.storyboard?.instantiateViewController(withIdentifier: "DefinitionViewController") as! DefinitionViewController

        //initialise data for the view controller
        ListViewController.initDetails(forKey: resultsArray[indexPath.row])

        performSegue(withIdentifier: "segue", sender: self)
        tableView.deselectRow(at: indexPath, animated: true)
 }

Definition Controller初始化详情:

func initDetails(forKey key: String) {
    definitionBody.text=dictionary[key]![0]
    definitionSources.text=dictionary[key]![1]
}

答案 1 :(得分:0)

我认为在我看来这是一个非常肮脏的解决方案,因为它需要保留两套标题,所以我仍然很好奇,如果有人知道更好的方法,但这确实有效:

如果搜索(为了避免在不需要的情况下调用开关),在didSelectRowAt indexPath下,我创建了一个开关,它基本上检查所选单元格的文本并相应地设置arrayIndex的值。

let selectedCell = tableView.cellForRow(at: indexPath)?.textLabel!.text ?? "Undefined"

       switch selectedCell {
       case "Anger": arrayIndex = 0
       case "Anguish": arrayIndex = 1
       case "Anxiety": arrayIndex = 2
       case "Annoyance": arrayIndex = 3
       case "Apathy": arrayIndex = 4
       default: print("Undefined Search Query")
       }

titles数组最终会有大约55个元素,我希望将所有数据保存在一个单独的Data.swift文件中,但这是我到目前为止唯一的解决方案。