I would like to present a new ViewController when user clicks element in tableviewcell. The standard code for launching a VC, however, does not work from a tableview cell or even in a helper class because neither a TVC nor a helper class can present a view controller.
Here is the code in a helper class. Whether placed in the helperclass or the tableview cell, it doesn't have a present method to launch a VC.
class launchVC {
func launchVCNamed(identifier: String) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyBoard.instantiateViewController(withIdentifier: "contactDetail")
//FOLLOWING LINE HAS ERROR NO SUCH MEMBER (present)
self.present(secondVC, animated: true, completion: nil)
}
}
How can I modify this to launch a VC?
Generally you should use delegate pattern, or closure to pass a block from cell back to view controller. I prefer using closures to delegates so I'll give such example:
class SomeCell: UITableViewCell {
var actionBlock = { }
func someActionOccured() { // some action like button tap in cell occured
actionBlock()
}
}
And in cellForRow in view controller you need to assign the closure
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SomeCell // replace cell identifier with whatever your identifier is
cell.actionBlock = { [unowned self] in
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyBoard.instantiateViewController(withIdentifier: "contactDetail")
self.present(secondVC, animated: true, completion: nil)
}
return cell
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With