首页 > 解决方案 > 如何在 swift 中编写 if/else 语句,以便在 iOS 表格视图中单击特定单元格时,它会转到特定的 viewController

问题描述

我有一个带有多个单元格的 tableView,这些单元格转到一个 viewController。I'm setting up a new viewController for a specific cell that, when selected, will open its own viewController for that specific cell. How do I add another if/else statements for a second cell when selected to go to its own ViewController which will be the third VC? 如何在 Swift 中正确实现这一点?

I already have one if/else statement that when the cell in section"0" row "0" is selected to go to the reciprocity view controller. 它工作正常,但是,如何在“0”行“20”部分为单元格添加另一个语句以转到其自己的 viewController。我是 swift 的新手,并试图正确学习。任何帮助将非常感激。

`override func tableView(_ tableView: UITableView, didSelectRowAt   indexPath: IndexPath) {
    if ((indexPath.section == 0) && (indexPath.row == 0)) {
        performSegue(withIdentifier: "reciprocityView", sender: nil);
    if ((indexPath.section == 0) && (indexPath.row == 20)) {
            performSegue(withIdentifier: "InterestViewController", sender: nil)
        }
    } else {
        let productLine = productLines[indexPath.section]
        let product = productLine.products[indexPath.row]
        selectedProduct = product
        performSegue(withIdentifier: "showProductDetail", sender: nil)}
}
    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if segue.identifier == "showProductDetail" {
            let DetailVC = segue.destination as!     DetailViewController
            DetailVC.product = selectedProduct
        }

        }
    }`    

由于我添加了 ((indexPath.section == 0) && (indexPath.row == 20,因此该单元格继续转到默认的 viewController 而不是 InterestViewController。

标签: iosswift

解决方案


您的第二个 if 语句永远不会触发,因为您是从第一个 if 语句内部调用它。单元格行不能同时为 0 和 20。在此之外您需要一个 else if 语句。

if condition {
   do something
} else if condition2 {
   do something else
} else {
   do something else
}

推荐阅读