单击TableViewCell时如何重定向到另一个视图控制器?

时间:2018-01-26 10:25:39

标签: ios uitableview swift4

我无法理解为什么当我点击TableViewCell

时它无法重定向到另一个View Controller

FirstViewController 是包含tableView

的视图控制器

SecondViewController 是我的设想

我已经完成的工作:

1)我将FirstViewController嵌入NavigationController

中的StoryBoard

2)我已经设置了从FirstViewControllerSecondViewController的show segue,并且已经将segue标识符设置为" GoToSecondViewController"

当然为了让我在tableViewCell中显示数据我有这个2函数:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.myCell.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCellClass
        cell.myCellList = self.myCell[indexPath.row]
        return cell
    }

3)在FirstViewController中,我已经尝试了以下2解决方案:

第一个解决方案:

  • 我在performSegue函数

    中调用didSelectRowAt
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.performSegue(withIdentifier: "GoToSecondViewController", sender: self)    
    }
    

第二个解决方案:

  • 我在didSelectRowAt函数

    中使用了navigationController?.pushViewController
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
    
        let controller = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
    
        self.navigationController?.pushViewController(controller, animated: true)
    
    }
    

我尝试了2个以上的解决方案,但没有产生任何结果。在查看this question后,我甚至在gestureRecognizer中停用了FirstViewController,仍然无法重定向到SecondViewController

所以我最后想要打印出这个值,但是在控制台中也没有打印出来的值:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")
    }

当我点击tableViewCell时,我试图重新定向到另一个视图控制器,但仍然无法正常工作。我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

在viewDidLoad

中添加此行
 tableview.delegate = self

答案 1 :(得分:0)

我终于明白了,我需要在StoryBoard中查看Single Selection的{​​{1}}选项。

像这样:

enter image description here

之前我将选择设置为无选择。因此导致上述问题。