Search code examples
swiftuitableviewuiviewcontrolleruinavigationcontroller

Navigate from a ViewController to an another on didSelectRowAt programmatically


I have a UIViewController that contains a custom UITableView. The table has a custom UITableViewCell too.

How to navigate from the first ViewController to an another when you select/click one of the rows?

Note

I have not used StoryBoard.

Update

This my code. Each one of the classes are external file. Let me know, if you need more code.

class TestViewController: UIViewController, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view.addSubview(testTableView)
    }

    let testTableView: TestTableView = {
        let table = TestTableView()
        table.register(TestTableViewCell.self, forCellReuseIdentifier: TestTableViewCell.identifier)
        return table
    }()
}

class TestTableView: UITableView,  UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: TestTableViewCell.identifier, for: indexPath)
        return cell
    }
}



class TestTableViewCell: UITableViewCell {
    static let identifier  = "testCell"
}

Solution

  • Here is a complete answer:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let newViewController = NewViewController()
        self.navigationController?.pushViewController(newViewController, animated: true)
    }