Search code examples
iosswiftxcode6uisearchdisplaycontroller

SearchDisplayController to detailedViewController


I have a problem. I have set up a table view with search bar. I want when a cell is clicked to present a detailed view controller. So far I have done that but when I search an item from the array and press it, it always displays the same detailed view controller (the view controller for indexPath.row == 0)

EDIT with the whole tableviewcontroller:

class CandyTableViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {

var person = [Candy]()
//add a filter
var filteredCandies = [Candy]()

@IBOutlet var myTableView: UITableView!


override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    navigationController?.navigationBar.tintColor = UIColor(red: 120, green: 113, blue: 165, alpha: 100)
}

override func viewDidLoad() {
    super.viewDidLoad()
            // Sample Data for candyArray

    navigationController?.navigationBar.barStyle = UIBarStyle.Default
    navigationController?.navigationBar.tintColor = UIColor(red: 120, green: 113, blue: 165, alpha: 100)


    self.person = [

        Candy(category:"За перфектна чревна флора", name:"Пробиен", imageName: "Probien1.png", testlabel: "проиен", latinNames: "probien"),

        Candy(category:"Подкрепа на вените", name:"Рувенор", imageName:"Ruvenor1.png", testlabel: "рувенор", latinNames: "ruvenor"),

        Candy(category:"Грижа за диабетиците",name: "Диабекан", imageName: "Diabekan1.png", testlabel: "диабекан", latinNames: "diabekan"),

        Candy(category:"Максимална грижа за простатата", name: "Простамакс", imageName: "Prostamaks1.png", testlabel: "простамакс", latinNames: "prostamaks"),

        Candy(category:"Женско здраве", name: "Агнес", imageName: "Agnes1.png", testlabel: "агнес", latinNames: "agnes"),

        Candy(category:"Капанът за мазнини", name: "Хитозан", imageName: "Hitozan1.png", testlabel: "хитозан", latinNames: "hitozan"),

        Candy(category:"Продукти с екстракт от гинко билоба", name: "Гинко синергия", imageName: "GinkoSinergiq1.png", testlabel: "гинко синергия", latinNames: "ginko sinergiq"),

        Candy(category:"За контрол на холестерола",name: "Нолипид", imageName: "Nolipid1.png", testlabel: "нолипид", latinNames: "nolipid"),

        Candy(category:"За нормална перисталтика", name: "Диарид про", imageName: "DiaridPro1.png", testlabel: "диарид про", latinNames: "diarid pro"),
        Candy(category:"За пациенти с ракови заболявания", name: "Авемар", imageName: "Avemar1.png", testlabel: "авемар", latinNames: "avemar"),
        Candy(category:"За здраво гърло и силен имунитет", name: "Фитолор", imageName: "Fitolor1.png", testlabel: "фитолор", latinNames: "fitolor")


    ]



    myTableView.separatorColor = UIColor.clearColor()

    searchDisplayController?.searchResultsTableView.rowHeight = 213
    searchDisplayController?.searchResultsTableView.separatorColor = UIColor.clearColor()


    myTableView.backgroundColor = UIColor(red: 120, green: 113, blue: 165, alpha: 1)

    // Reload the table
    self.tableView.reloadData()
}

// MARK: - Table view data source


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if tableView == self.searchDisplayController!.searchResultsTableView {


                    return self.filteredCandies.count
    } else {
        return self.person.count
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellTableViewCell

    var candy : Candy

    // Check to see whether the normal table or search results table is being displayed and set the Candy object from the appropriate array

    if tableView == self.searchDisplayController!.searchResultsTableView {


        candy = filteredCandies[indexPath.row]

    } else {
        candy = person[indexPath.row]

    }

    cell.label1.text = candy.name
    cell.label2.text = candy.category


    //cell.contentView.frame = cell.bounds
    cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

   // let item = candies[indexPath.row]
    cell.setCell(candy.name, label2Text: candy.category, image1: candy.imageName, testlabel: candy.testlabel, latinNames: candy.latinNames)

    return cell
}


override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    var candy : Candy

    if (tableView == self.searchDisplayController?.searchResultsTableView)
    {

        candy = self.filteredCandies[indexPath.row]
        if (indexPath.row == 0){

            // Present Your first view controller

            let detailedViewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController

            self.presentViewController(detailedViewController, animated: true, completion: nil)


        }else if (indexPath.row == 1){
            // Present Second view controller

            let detailedViewController1: PageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProductsPageViewController") as! PageViewController

            self.presentViewController(detailedViewController1, animated: true, completion: nil)

        } else if (indexPath.row == 2){

            let detailedViewController2: DiabekanThirdCellPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DiabekanPageViewController") as! DiabekanThirdCellPageViewController

            self.presentViewController(detailedViewController2, animated: true, completion: nil)

        } else if (indexPath.row == 3){

            let detailedViewController3: ProstamaksPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProstamaksPageViewController") as! ProstamaksPageViewController

            self.presentViewController(detailedViewController3, animated: true, completion: nil)

        } else if (indexPath.row == 4){
            let detailedViewController4: AgnesPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AgnesPageViewController") as! AgnesPageViewController

            self.presentViewController(detailedViewController4, animated: true, completion: nil)

        } else if (indexPath.row == 5){
            let detailedViewController5: HitozanPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("HitozanPageViewController") as! HitozanPageViewController

            self.presentViewController(detailedViewController5, animated: true, completion: nil)

        } else if (indexPath.row == 6){

            let detailedViewController6: GinkoSinergiqPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("GinkoSinergiqPageViewController") as! GinkoSinergiqPageViewController

            self.presentViewController(detailedViewController6, animated: true, completion: nil)


        } else if (indexPath.row == 7){

            let detailedViewController7: NolipidPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("NolipidPageViewController") as! NolipidPageViewController

            self.presentViewController(detailedViewController7, animated: true, completion: nil)


        }else if (indexPath.row == 8){

            let detailedViewController8: DiaridPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DiaridPageViewController") as! DiaridPageViewController

            self.presentViewController(detailedViewController8, animated: true, completion: nil)


        }else if (indexPath.row == 9){

            let detailedViewController9: AvemarPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AvemarPageViewController") as! AvemarPageViewController

            self.presentViewController(detailedViewController9, animated: true, completion: nil)


        }else if (indexPath.row == 10){

            let detailedViewController10: FitolorPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("FitolorPageViewController") as! FitolorPageViewController

            self.presentViewController(detailedViewController10, animated: true, completion: nil)



        }else if (indexPath.row == 11){

        }
    }
    else
    {
        candy = self.person[indexPath.row]

        if (indexPath.row == 0){

            // Present Your first view controller

            let detailedViewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController

            self.presentViewController(detailedViewController, animated: true, completion: nil)


        }else if (indexPath.row == 1){
            // Present Second view controller

            let detailedViewController1: PageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProductsPageViewController") as! PageViewController

            self.presentViewController(detailedViewController1, animated: true, completion: nil)

        } else if (indexPath.row == 2){

            let detailedViewController2: DiabekanThirdCellPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DiabekanPageViewController") as! DiabekanThirdCellPageViewController

            self.presentViewController(detailedViewController2, animated: true, completion: nil)

        } else if (indexPath.row == 3){

            let detailedViewController3: ProstamaksPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProstamaksPageViewController") as! ProstamaksPageViewController

            self.presentViewController(detailedViewController3, animated: true, completion: nil)

        } else if (indexPath.row == 4){
            let detailedViewController4: AgnesPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AgnesPageViewController") as! AgnesPageViewController

            self.presentViewController(detailedViewController4, animated: true, completion: nil)

        } else if (indexPath.row == 5){
            let detailedViewController5: HitozanPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("HitozanPageViewController") as! HitozanPageViewController

            self.presentViewController(detailedViewController5, animated: true, completion: nil)

        } else if (indexPath.row == 6){

            let detailedViewController6: GinkoSinergiqPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("GinkoSinergiqPageViewController") as! GinkoSinergiqPageViewController

            self.presentViewController(detailedViewController6, animated: true, completion: nil)


        } else if (indexPath.row == 7){

            let detailedViewController7: NolipidPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("NolipidPageViewController") as! NolipidPageViewController

            self.presentViewController(detailedViewController7, animated: true, completion: nil)


        }else if (indexPath.row == 8){

            let detailedViewController8: DiaridPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DiaridPageViewController") as! DiaridPageViewController

            self.presentViewController(detailedViewController8, animated: true, completion: nil)


        }else if (indexPath.row == 9){

            let detailedViewController9: AvemarPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AvemarPageViewController") as! AvemarPageViewController

            self.presentViewController(detailedViewController9, animated: true, completion: nil)


        }else if (indexPath.row == 10){

            let detailedViewController10: FitolorPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("FitolorPageViewController") as! FitolorPageViewController

            self.presentViewController(detailedViewController10, animated: true, completion: nil)



        }else if (indexPath.row == 11){

        }

    }

}

   /* let infoViewController: InfoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("InfoViewController") as! InfoViewController

    infoViewController.label01 = candy.name
    infoViewController.label02 = candy.category
    infoViewController.imageFile = candy.imageName

     self.presentViewController(infoViewController, animated: true, completion: nil)
} */

func filterContentForSearchText(searchText: String, scope: String = "All") {
    // Filter the array using the filter method

    self.filteredCandies = self.person.filter({( candy: Candy ) -> Bool in

        let categoryMatch = (scope == "All") || (candy.category == scope)
        let categoryMatch1 = (scope == "All") || (candy.name == scope)
        let categoryMatch2 = (scope == "All") || (candy.name == scope)
        let categoryMatch3 = (scope == "All") || (candy.name == scope)
        let categoryMatch4 = (scope == "All") || (candy.name == scope)


        let stringMatch = candy.name.rangeOfString(searchText)
        let stringMatch1 = candy.category.rangeOfString(searchText)
        let stringMatch2 = candy.testlabel.rangeOfString(searchText)
        let stringMatch3 = candy.imageName.rangeOfString(searchText)
        let stringMatch4 = candy.latinNames.rangeOfString(searchText)

        return categoryMatch && (stringMatch != nil) || categoryMatch1 && (stringMatch1 != nil) || categoryMatch2 && (stringMatch2 != nil) || categoryMatch3 && (stringMatch3 != nil) || categoryMatch4 && (stringMatch4 != nil)


    })



}


func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText(searchString)


            return true
}

func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
    self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
    return true
}

}


Solution

  • Here's my attempt at solving the problem with the information given:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
    
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    
        var candy : Candy
    
        if (tableView == self.searchDisplayController?.searchResultsTableView)
        {
            candy = self.filteredCandies[indexPath.row]
        }
        else {
            candy = self.person[indexPath.row]
        }
    
        var detailedViewController: UIViewController!
    
        switch candy.name {
        case "Пробиен" :
    
            // Present Your first view controller
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
    
            break
        case "Рувенор" :
    
            // Present Second view controller
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProductsPageViewController") as! PageViewController
    
            break
        case "Диабекан" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DiabekanPageViewController") as! DiabekanThirdCellPageViewController
    
            break
        case "Простамакс" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProstamaksPageViewController") as! ProstamaksPageViewController
    
            break
        case "Агнес" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AgnesPageViewController") as! AgnesPageViewController
    
            break
        case "Хитозан" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("HitozanPageViewController") as! HitozanPageViewController
    
            break
    
        case  "Гинко синергия" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("GinkoSinergiqPageViewController") as! GinkoSinergiqPageViewController
    
            break
        case "Нолипид" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("NolipidPageViewController") as! NolipidPageViewController
    
            break
        case "Диарид про" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DiaridPageViewController") as! DiaridPageViewController
    
            break
        case "Авемар" :
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AvemarPageViewController") as! AvemarPageViewController
    
            break
        case "Фитолор":
    
            detailedViewController = self.storyboard?.instantiateViewControllerWithIdentifier("FitolorPageViewController") as! FitolorPageViewController
    
            break
        default:
            break
        }
    
        if detailedViewController != nil {
            self.presentViewController(detailedViewController, animated: true, completion: nil)
        }
    
    }
    

    This is a replacement for your didSelectRowAtIndex function. This filters based on the Candy.name property. If this is not what you're looking for, then please let me know what is wrong with it and I will adjust accordingly.