1

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.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Ace
  • 603
  • 2
  • 15
  • 33

3 Answers3

0

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

}
Hossam Ghareeb
  • 7,063
  • 3
  • 53
  • 64
  • Is the reason because indexPath is more accurate? or is that just proper practice? and also Thank you – Ace Oct 18 '15 at 14:35
  • Its more accurate as you compare integers not strings. As well its best practice, suppose you changed the displayed text anytime, in case of strings, you have to change the comparison code but in case of using indexPath, you don't – Hossam Ghareeb Oct 19 '15 at 05:15
  • what means other. other name or other think? – jcmaxuser Sep 14 '16 at 19:14
0

Yes, you can.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    if cell.cellLabel.text == "option8" {
        self.performSegueWithIdentifier("other8", sender: self)
    }
}
t4nhpt
  • 5,264
  • 4
  • 34
  • 43
0

You can check indexpath.row in didSelectrow according to row no you can redirect to perticular controller.

user3306145
  • 76
  • 2
  • 12