juelizabeth
juelizabeth

Reputation: 505

UISearchController Segue

I have a tableview with 5 cells in a tableviewcontroller. I want all the cells to segue to a searchtableviewcontroller. However, each cell is a different subject and when I click on one cell, I want the cell to segue to its corresponding subject. This is the searchtableviewcontroller.

import UIKit
import Firebase
import FirebaseDatabase

class SearchTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {

    @IBOutlet var followUsersTableView: UITableView!
    let searchController = UISearchController(searchResultsController: nil)



    var usersArray = [NSDictionary?]()
    var filteredUsers = [NSDictionary?]()

    var databaseRef = FIRDatabase.database().reference()
    var infoRef = FIRDatabase.database().reference().child("info")
    var loggedInUser = FIRAuth.auth()?.currentUser
    let userID = FIRAuth.auth()?.currentUser?.uid
    var posts = NSMutableArray()
    var loggedUser:FIRUser?






    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true
        tableView.tableHeaderView = searchController.searchBar

        searchController.searchBar.isTranslucent = false

        searchController.searchBar.tintColor = UIColor(red:0.23, green:0.73, blue:1.00, alpha:1.0)
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.placeholder = "Search Books by Title, Author & ISBN"
        searchController.searchBar.delegate = self
        searchController.searchBar.sizeToFit()
        self.searchController.hidesNavigationBarDuringPresentation = false
        self.navigationItem.title = "Search Books"


      databaseRef.child("books").observe(.childAdded, with: { (snapshot) in


        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary
        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedUser?.uid)
        {
            print("same as logged in user")
        }
        else
        {
        self.usersArray.append(snapshot)
             self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
        }



        }) { (error) in
            print(error.localizedDescription)
        }

    }




    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows


        if searchController.isActive && searchController.searchBar.text != ""{
            return filteredUsers.count
        }
        return self.usersArray.count

    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! TableViewCell

        let user : NSDictionary?

        if searchController.isActive && searchController.searchBar.text != ""{
            user = filteredUsers[indexPath.row]
        }
        else
        {
            user = self.usersArray[indexPath.row]
        }

        cell.Title.text = user?["title"] as? String
        cell.Author.text = user?["Author"] as? String
        cell.ISBN.text = user?["ISBN"] as? String
        cell.Price.text = user?["Price"] as? String
        if let imageName = user?["image"] as? String {
            let imageRef = FIRStorage.storage().reference().child("images/\(imageName)")
            imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in
                if error == nil {

                    let image = UIImage(data: data!)
                    cell.Book.image = image

                }else {
                    print("Error downloading image:" )
                }})}

        cell.detailTextLabel?.text = user?["handle"] as? String




        return cell
    }


    func filtereContent(searchText: String)
    {
        self.filteredUsers = self.usersArray.filter{user in
           // let typeMatch = (scope == "Title") || (user?.fileType() == scope)
            let title = user!["title"] as? String
            let author = user!["Author"] as? String
            let isbn = user!["ISBN"] as? String


            return(title?.lowercased().contains(searchText.lowercased()))! || (author?.lowercased().contains(searchText.lowercased()))! || (isbn?.lowercased().contains(searchText.lowercased()))!

        }
        tableView.reloadData()

    }
}


extension SearchTableViewController{
    func updateSearchResults(for searchController: UISearchController) {

        filtereContent(searchText: self.searchController.searchBar.text!)

    }

}

This is my tableviewcontroller that has the cells to be selected.

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myIndex = indexPath.row

        if indexPath.section == 0 && indexPath.row == 0{
            performSegue(withIdentifier: "segue", sender: self)
        }
        else if indexPath.section == 0 && indexPath.row == 1{
        }
        else if indexPath.section == 0 && indexPath.row == 2{
        }
        else if indexPath.section == 0 && indexPath.row == 3{
        }
        else
        {

        }
        }

Upvotes: 0

Views: 281

Answers (1)

Kirill Korolev
Kirill Korolev

Reputation: 1006

Practically you should use didSelectRowAtIndexPath delegate's method and invoke performSegueWithIdentifier to your SearchViewController using segue identifier.

self.performSegueWithIdentifier(YOUR_SEGUE_ID, sender: self)

In this method you probably want to memorize the index of your selected object, so I propose you to create a sort of a global variable that stores selected index.

selectedIndex = indexPath.row

Then in prepareForSegue method you have an access to destionationViewController property. You should explicitly specify the proper view controller

var destinationVC = segue.destinationViewController as! YOUR_VIEW_CONTROLLER_CLASS

After these trivial manipulations you have a free access to all public variables and properties of SearchViewController class. So, you are able to pass selectedIndex to this view controller.

For instance:

destinationVC.selectedIndex = selectedIndex

And eventually in a viewDidLoad in SearchViewController you can appeal to this variable to get the proper item from your array to show the corresponding data.

Upvotes: 3

Related Questions