简体   繁体   中英

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.

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

}

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

您可以根据行在didSelectrow中检查indexpath.row,否,您可以重定向到垂直控制器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM