'Open a ViewController if a cell of a TableViewController is clicked

i'm trying to create a view controller programmatically that will be opened if a cell on a table is clicked. i'm using a table view and i'm filling it with a xib.So, i'm stuck at the point of referencing the new view controller from the first one on click on a cell created in the table view via xib.

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "DViewController") as? DViewController
    self.navigationController?.present(vc!, animated: true, completion: nil) //present della view successiva
    vc?.name = data[indexPath.row].nome
    
}

this code allows me to click on the row but when clicked it shows an error "Fatal error: Unexpectedly found nil while unwrapping an Optional value" generated apparently from the self.navigationController?.present(vc!...the vc value result to be nil and i can't figure out why. THis is the ViewController that i want to open on click and the only thing that it has to do is open and change the tile to the name ow the cell that i've clicked onto in the other ViewController

class DViewController: UITableViewController {

var name = ""

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.navigationBar.topItem?.title = "\(name)"
}

}

Can someone help?i'm new to swift...ty



Solution 1:[1]

Based on what you mentioned. You can initialize your viewController without stroyboard, and there is no crash anymore.

let vc = DViewController()

If you present your view controller like what you did, it won’t display the title you wish. To display the title, there are 2 ways you can do:

Display your new view controller with Pushing style:

let vc = DViewController() 
navigationController?.pushViewController(vc, animated: true)

Keep using presenting style, but you need to wrap your view controller in other navigation controller:

let vc = DViewController()
let nav = UINavigationController(rootViewController: vc)
navigationController?.present(nav, animated: true)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sereysophea Eap