0

I want to navigate from UITableViewCell(Xib) to UIViewController but when I try to use present Value of type 'TableViewCell' has no member 'present So if anyone is familiar with a function that can help me navigate please help me :) .

Thank you for your time

Nessrine Hafi
  • 87
  • 2
  • 16
  • you can use tableview `didSelectRowAt`, and from that your controller (a.k.a self), has the "self.present...." – Gustavo Vollbrecht Aug 30 '19 at 12:17
  • @GustavoVollbrecht yes it's a good idea but what if inside the tableviewcell there's a button and we want that button to navigate us instead of the whole cell – Nessrine Hafi Aug 30 '19 at 12:22

3 Answers3

2

UITableViewCell can’t present viewcontroller. Please store viewController to variable in your tableview cell. And use it to present. Or use didSelectRowAt delegate function and using self to present ( Or write your custom cell delegate if your event fire by button in cell)

Thanh Vu
  • 1,599
  • 10
  • 14
2

Conform your ViewController to UITableViewDelegate protocol and then in your ViewController code use the delegate method: func tableView(UITableView, didSelectRowAt: IndexPath) and inside this method perform/present a segue or any other type of navigation you have.

import UIKit

class ViewController: UIViewController, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }   

    func tableView(UITableView, didSelectRowAt: IndexPath) {
            // navigation logic here
    }


}
1

Use closure inside your custom UITableViewCell to handle this scenario.

In your custom UITableViewCell create a handler and call it when the button is tapped inside the cell, i.e.

class CustomCell: UITableViewCell {
    var handler: (()->())?

    @IBAction func onTapButton(_ sender: UIButton) {
        handler?()
    }
}

Now, set the handler in cellForRowAt when creating the cell, i.e.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
    cell.handler = {
        //present your controller here...
    }
    return cell
}
PGDev
  • 23,751
  • 6
  • 34
  • 88