0
votes

I have a UITableView that is populated with items from a titles array and I have it setup so that when didSelectRowAt indexPath is called, a variable called arrayIndex is changed to the indexPath and the content of the next VC is changed.

So if a user taps on:

  • Row 0 > VC will have Title 0, Definition 0 and Link 0
  • Row 12 > VC will have Title 12, Definition 12 and Link 12

I have a search bar however that stores the filtered results in a searchResults array and displays them in the tableView. When a search is performed, the array index will no longer correspond, so if the search query changes the tableview to

  • Title 4 on Row 0 > VC will have Title 0, Definition 0 and Link 0
  • Title 5 on Row 1 > VC will have Title 1, Definition 1 and Link 1
  • Title 18 on Row 2 > VC will have Title 2, Definition 2 and Link 2

I understand why it doesn't work as expected, but I am not sure how to update my logic to fix it. Thoughts? Here is my code:

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)

    }   
}

Definition Controller:

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

2 Answers

1
votes

Try using a dictionary where the key is your title and its value its a dictionary containing the definition and link, and an array where you will store the search results i.e the keys searched.

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()
    }
}

Now when you tap on a cell in the List Controller let it know which key's details you want to initialise and load in the next 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)
 }

In your Definition Controller initialise the details:

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

I thought of what seems to me like a pretty dirty solution, because it requires keeping two sets of titles, so I'm still curious if anyone knows a better way, but this does work:

If searching (to avoid calling the switch if it's not needed), under didSelectRowAt indexPath, I created a switch that essentially checks the text of the selected cell and sets the value of arrayIndex accordingly.

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")
       }

The titles array will eventually have some 55 elements and I had hoped to keep all the data in a separate Data.swift file, but this is the only solution I have so far.