UITableView: Click a Cell and trigger a new SwiftUI view

Viewed 24

I have the following code, there are 2 things that I have to do, once the Cell is selected (already doing it), to launch a new View, the new view has to be a SwiftUI view, I have attached an image of the current app running, any assistance will be appreciated, thanks

import UIKit

var rows = ["A", "B", "C", "D"]

class ViewController: UIViewController  {
    let uiKitTableView = UITableView()
    override func viewDidLoad() {
        super.viewDidLoad()
        configUITableView()
        self.uiKitTableView.register(UITableViewCell.self, forCellReuseIdentifier: "tablecell")
        let indexPath = IndexPath(row: 0, section: 0)
        self.uiKitTableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
    }
    override func viewDidLayoutSubviews() {
        super.viewWillLayoutSubviews()
        uiKitTableView.frame = view.bounds
    }
    func configUITableView() {
        view.addSubview(uiKitTableView)
        uiKitTableView.delegate = self
        uiKitTableView.dataSource = self
        uiKitTableView.rowHeight = 50
    }
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let uiTableViewCell = tableView.dequeueReusableCell(withIdentifier: "tablecell", for: indexPath)
        uiTableViewCell.textLabel?.text = " \(rows[indexPath.row])"
        return uiTableViewCell
    }
}

Print Screen App running

1 Answers

In UITableView didSelectRowAt you can open SwiftUI View by using this lines of code:

let swiftUIController = UIHostingController(rootView: SwiftUIView())
navigationController?.pushViewController(swiftUIController, animated: true)

And don't forget to import SwiftUI.

Related