以编程方式从ViewController导航到didSelectRowAt上的另一个

时间:2018-10-27 10:15:50

标签: swift uitableview uiviewcontroller uinavigationcontroller

我有一个UIViewController,其中包含一个自定义的UITableView。该表也具有自定义UITableViewCell

当您选择/单击其中的一行时,如何从第一个ViewController导航到另一个?

注意

我还没有使用StoryBoard

更新

这是我的代码。每个类都是外部文件。让我知道,如果您需要更多代码。

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

3 个答案:

答案 0 :(得分:1)

这是一个完整的答案:

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

答案 1 :(得分:0)

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let vc = yourCustomVCName (nibName: "yourCustomVC nibName" , bundle : nil)
     self.present(vc, animated: true , completion: nil)  
}

答案 2 :(得分:0)

UIKit以编程方式对TableCell进行导航,而无需情节提要。 您有两种查看下一个viewController的方法

  1. 如果您想展示.......

从底部到顶部进行动画

yourTableView.deselectRow(at: indexPath, animated: true)//used for single Tap
let vC = YourViewController (nibName: "" , bundle : nil)
        vC.modalPresentationStyle = .fullScreen //this line is optional for fullscreen
        self.present(vC, animated: true , completion: nil)
  1. 或者如果您想正常查看viewController(连击2个)....

从右向左动画

yourTableView.deselectRow(at: indexPath, animated: true)
let vC = YourViewController()
self.navigationController?.pushViewController(vC, animated: true)
相关问题