Navigate from a ViewController to an another on didSelectRowAt programmatically

。_饼干妹妹 提交于 2020-12-15 07:07:24

问题


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

回答1:


Here is a complete answer:

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



回答2:


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



回答3:


UIKit Programmatically TableCell Navigate without storyboard. you have two ways to View next viewController

  1. If you want to present .......

animating from bottom to top

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. Or if you want to View your viewController normally (2 is batter) ....

animate from right to left

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


来源:https://stackoverflow.com/questions/53020856/navigate-from-a-viewcontroller-to-an-another-on-didselectrowat-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!