点击 tableview 中的单元格时没有任何反应

Nothing happens when cell from tableview is tapped

我创建了一个 tableview 菜单,当您点击一个单元格以显示特定的故事板时,我想要它。菜单由 4 个单元格(因此 4 个不同的故事板)格式化

这是我的代码:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        _ = tableView.indexPathForSelectedRow!
        if let _ = tableView.cellForRowAtIndexPath(indexPath){
        if indexPath.row == 0{
            print("User choose to buy ticket")
            self.storyboard?.instantiateViewControllerWithIdentifier("SearchPage")
        }else if indexPath.row == 1{
            print("User choose to check the train status")
            self.storyboard?.instantiateViewControllerWithIdentifier("TrainStatusPage")
        }else if indexPath.row == 2{
            print("User choose to see the upcoming trips")
            self.storyboard?.instantiateViewControllerWithIdentifier("TripsPage")
        }else if indexPath.row == 3{
            print("User wants to know mor about CFR's facility")
            self.storyboard?.instantiateViewControllerWithIdentifier("PassengersPage")
        }
        }
    }

当我按下单元格时(不管是哪个单元格),单元格变成灰色并且没有任何反应。

您不需要使用这行代码: _ = tableView.indexPathForSelectedRow! 如果让 _ = tableView.cellForRowAtIndexPath(indexPath){

只需检查方法 didSelectRowAtIndexPath 收到的 indexPath.row。

所以正确的方法应该是这样的:

if indexPath.row == 0{
            print("User choose to buy ticket")
            self.storyboard?.instantiateViewControllerWithIdentifier("SearchPage")
        }else if indexPath.row == 1{
            print("User choose to check the train status")
            self.storyboard?.instantiateViewControllerWithIdentifier("TrainStatusPage")
        }else if indexPath.row == 2{
            print("User choose to see the upcoming trips")
            self.storyboard?.instantiateViewControllerWithIdentifier("TripsPage")
        }else if indexPath.row == 3{
            print("User wants to know mor about CFR's facility")
            self.storyboard?.instantiateViewControllerWithIdentifier("PassengersPage")
        }

并且您可以添加此行以从单元格中删除选择状态:

tableView(tableView: UITableView, didSelectRowAtIndexPath

您可能打算导航到下一个 viewController?那么你需要这么说,初始化一个实例只是工作的一半(如果这确实是你想要做的)。所以 一些东西 像下面这样:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var viewController: UIViewController?
    if indexPath.row == 0 {
        viewController = storyboard?.instantiateViewControllerWithIdentifier("SearchPage")
    }else if indexPath.row == 1 {
        viewController = storyboard?.instantiateViewControllerWithIdentifier("TrainStatusPage")
    }else if indexPath.row == 2 {
        viewController = storyboard?.instantiateViewControllerWithIdentifier("TripsPage")
    }else if indexPath.row == 3 {
        viewController = storyboard?.instantiateViewControllerWithIdentifier("PassengersPage")
    }

    if let destination = viewController {
        navigationController?.pushViewController(destination, animated: true)
    }
}