Search code examples
iosswiftuitableviewxcode7

Directing to a different ViewController depending on tableView cell clicked


I am trying to present a viewController depending on which tableView cell is clicked.

Currently if they are all clicked they redirect to the same viewController, how would I alter this?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
    cell.cellLabel.text = self.objects.objectAtIndex(indexPath.row) as! String

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("other", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "other"){

        var upcoming: otherViewController = segue.destinationViewController as! otherViewController

        let indexPath = self.tableView.indexPathForSelectedRow!

        let titleString = self.objects.objectAtIndex(indexPath.row) as! String

        upcoming.titleString = titleString

        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)


    }
}

Could I do an if else on the cellLabel.text? as in if (cellLabel.text == "option8"){ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("option8", sender: self) }

}

I am using Swift and xcode7.


Solution

  • Don't and never do comparision with cellLabel.text, consider using indexPath.row for that. Then adding different segues in your storyboard for each view controller you need. Code will be something like that:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == 0 || indexPath.row == 2{
       self.performSegueWithIdentifier("other", sender: self)
    }
    else{
      self.performSegueWithIdentifier("other", sender: self)
    }
    
    }