15

I am trying to make it where when a user clicks on a table view cell in my table view it takes them to a new view controller. More specifically, when a user clicks on a persons username it should take them to that users profile. the username being the table view cell and the profile being the new view controller. I thought the way to do this was to use the ".presentViewController(vc, animated: true, completion: nil) however when i do this it says "myCell does not have a member named .presentViewController"Below is a screenshot of the issue

If anyone could help me solve this problem it'd be greatly appreciated

Ronald Jones
  • 201
  • 1
  • 2
  • 4

4 Answers4

21

The presentViewController:animated:completion is an instance method of the UIViewController not UIView or a subclass of. You can try this:

self.window?.rootViewController.presentViewController(specificViewController, animated: true, completion: nil)

However, I suggest that you should use the presentViewController:animated:completion: method from UIViewController. A callback mechanism can be achieved between the UIViewController and the cell.

Like so:Get button click inside UI table view cell

Community
  • 1
  • 1
Bannings
  • 10,228
  • 7
  • 42
  • 54
12

Banning's answer works, however the syntax is old. From Swift 4:

self.window?.rootViewController?.present(vc, animated: true, completion: nil)
Maciej Jureczko
  • 1,510
  • 6
  • 18
  • 22
The Doctor
  • 466
  • 1
  • 6
  • 15
3

swift3 version

let storyboard = UIStoryboard(name: "MainViewController", bundle: nil)
let messagesViewController = storyboard.instantiateViewController(withIdentifier: "MessagesViewController") as! MessagesViewController
self.window?.rootViewController?.present(messagesViewController, animated: true, completion: nil)
Alap Anerao
  • 1,978
  • 18
  • 26
Ahmed Safadi
  • 4,053
  • 35
  • 31
1

If you have created a separate class for tableView which is a good practice then, you can do it like this:

First, create addTarget where the cell is created (cellForRowAt):

cell.dropdownBtn.addTarget(self, action: #selector(self.openListPickerVC(_:)), for: .touchUpInside)

After that, present view controller in openListPickerVC():

@objc func openListPickerVC(_ sender: UIButton) {
    let index = sender.tag
    let vc: PickerViewController = UIStoryboard(name: "Main", bundle: 
             Bundle.main).instantiateViewController(withIdentifier: 
             "PickerViewController") as! PickerViewController

     self.present(vc, animated: true, completion: nil)
}
Ashay
  • 43
  • 7