根据单击的 tableView 单元格指向不同的 ViewController

Directing to a different ViewController depending on tableView cell clicked

我试图根据单击的 tableView 单元格显示 viewController。

目前,如果它们都被点击,它们会重定向到同一个 viewController,我该如何更改它?

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)


    }
}

我可以在 cellLabel.text 上做一个 if else 吗?如 if (cellLabel.text == "option8"){ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("option8", 发件人: 自己) }

}

我正在使用 Swift 和 xcode7。

不要也永远不要与 cellLabel.text 进行比较,请考虑使用 indexPath.row。然后在故事板中为您需要的每个视图控制器添加不同的 segues。代码将是这样的:

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

}

是的,你可以。

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 根据行号你可以重定向到特定的控制器。