Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presenting a View Controller with a button in a UITableViewCell programmatically (Swift)

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

like image 842
Ronald Jones Avatar asked Jun 09 '15 15:06

Ronald Jones


3 Answers

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

like image 101
Bannings Avatar answered Nov 15 '22 20:11

Bannings


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

self.window?.rootViewController?.present(vc, animated: true, completion: nil)
like image 40
The Doctor Avatar answered Nov 15 '22 20:11

The Doctor


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)
like image 35
Ahmed Safadi Avatar answered Nov 15 '22 22:11

Ahmed Safadi